0% found this document useful (0 votes)
11 views15 pages

Python New

This document is a comprehensive introduction to Python programming, covering basic concepts such as data types, variables, operators, control flow, functions, and object-oriented programming. It includes examples of code snippets demonstrating various features like loops, conditionals, and class definitions. The document serves as a practical guide for beginners to learn and practice Python programming.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views15 pages

Python New

This document is a comprehensive introduction to Python programming, covering basic concepts such as data types, variables, operators, control flow, functions, and object-oriented programming. It includes examples of code snippets demonstrating various features like loops, conditionals, and class definitions. The document serves as a practical guide for beginners to learn and practice Python programming.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 15

# FIRST PRACTICE IN PYTHON PROGRAMMING

print("hello world")
x = 5
y = "john"
print(x)
print(y)

# we used one variable to run different data type, python is not static
number = 10
print(f"original number: {number}")

number = "hello"
print(f"updated number: {number}")

number = [1, 2, 3]
print(f"updated number:{number}")

# want to specify a data type it can be done with casting:


float_number = 3.14
print(f"original float number:{float_number}")

int_number = int(3.14)
print(f"converted to integer:{int_number}")

float_number_again = float(3.14)
print(f"converted back to float:{float_number_again}")

# to get the data type of variable with the type() function:


x = 5
y = "john"
print(type(x))
print(type(y))

# boolean values
print(10 > 9)
print(10 == 10) # the == is figuring out if what is at the left is the same as
what is at the right
print(10 < 9)

# a message to check whether it is true or false


a = 200
b = 33
result = b > a
print(result)

# string as a topic
str1 = "hello"
str2 = "world"
result = str1 + " " + str2
print(result)

# string length
text = 'python is amazing'
length = len(text)
print("length", length)

# string indexing
word = 'python'
first_letter = word[0]
print("first letter", first_letter)

# logical operators
x = 4
print(x < 5 and x < 10)

x = 4
print(x < 5 or x < 3)

x = 4
print(not (x < 5 or x < 3))

# python identity operators


x = 4
y = x
print(x is y)

x = 4
y = 5
c = y
print(x is not c)

# python membership operators; used to check if a sequence is presented in an


object
x = [1, 2, 4]
y = 2
print(y in x) # returns true if a sequence with the specified value is present
in the object

x = [1, 2, 4]
y = 3
print(y not in x) # returns true if the

x = 5
y = 10
result = x == y
print(result)

string1 = 'hello'
string2 = 'world'
result = string1 == string2
print(result)

x = 5
print("original value of x :", x)

x = 10*2
print("new value:", x)

if 5 > 2:
print("obi is a boy!")
print("ada is a girl")

pen= 67889994
kane = "my name is vincent i cant type very well"
print( type(pen))
print(type(kane))

x = float(56783288)
print(x)

x, y, z, = "pink", "obi", "kane"


print ( z)

t = "fantastic"
def myfunc():
t = "fantastic"
print("Python is " + t)

import random
# for generating random numbers
print(random.randrange(1,10))

# how to loop string in python


for x in "antimolopologeographicationalism":
print(x)

# to check string
made = " camon20 is bigger and better than infinix note20"
if "could" not in made:
print("yes 'could' not inside the sentence.")

# indexing in list
my_list = [10, 20, 30,40,50]
first_element = my_list[1]
print("first element:", first_element)

# indexing in string
my_string = "python"
come = my_string[4]
print('first character', come)

# negative indexing : start from the back from -1


me = [1, 2, 3, 4]
mre = me[-3]
print ('coreect:', mre)

#identation
x = 10
if x > 12:
print("correct it is greater")
else:
print("oh no it is not")

# iteration
#definite iteration
for i in range(4):
print(i)

#indifinite iteration
num = 0
while num < 5:
print(num)
num +=1 # mean num = num + 1
# # while loop
# count = 0
# while count < 5:
# print ("count:", count)
# count +=1

#count down timer using a while loop


countdown = 10
while countdown >0:
print( countdown)
countdown -=1
print("blast off")

# user input validation using while loop


password = "password123"
user_input = input("Enter a password:")
while user_input != password: # != MEANING IF IT NOT CORRECT
print("incorrect password.try again.")
user_input = input("Enter the password:")
print("Access granted!")

# example of encapsulation
class Bankaccount:
def __int__(self, account_number, balance):
self._account_number = account_number
self._balance = balance
def get_account_number(self):
return self._account_number
def get_balance(self):
return self._balance
def deposit(self, amount):
self._balance += amount
def withdraw(self, amount):
if self._balance >= amount:
self._balance -= amount
else:
print("insufficient funds")

# creating an instance of the class


Account = Bankaccount ("123456789" , 1000)

# accessing attributes and methods


print("Account Number:", Account.get_account_number())
print("balance:", Account.get_balance())

Account.deposit(500)
print("balance after deposit:", Account.get_balance())

Account.withdraw(200)
print("Balance after withdrawal:", Account.get_balance())

Account.withdraw(2000)
# # # list
# # my_list = [1, 2, 3, 4, 5]
# # print(my_list)
# #
# # # tuple
# # my_tuple = (1, 2, 3, 4, 5)
# # print(my_tuple)
# #
# # # strings
# # my_string = "what can you do with 200 million dollars?"
# # print(my_string)
# #
# # # ranges
# # my_range = list(range(2, 60))
# # print(my_range)
# #
# # # ..............sequence methods>>>>>>>>>>>>
# # # len()
# # my_list = [1, 2, 3, 4, 5, 6]
# # length = len(my_list)
# # print(length)
# #
# # # index() Returns the index of the first occurrence of a value
# # my_list = [1, 2, 3, 4, 5, 6]
# # index = my_list.index(6)
# # print(index)
# #
# # # count() returns the number of occurrences of a value
# # my_list = [1, 2, 3, 1, 3, 3, 4, 5, 6]
# # count = my_list.count(3)
# # print(count)
#
# # append()
# my_list = [1, 2, 3]
# my_list.append(4)
# print(my_list)
#
# # insert()
# my_list = [1, 2, 3,]
# my_list.insert(2, 6)
# print(my_list)
#
# # remove()
# my_list = [1, 2, 3, 4, 3, 1]
# my_list.remove(3)
# print(my_list)
#
# # pop()
# my_list = [1, 2, 3, 4, 5, 6]
# element = my_list.pop()
# print(element)
#
# # reverse()
# my_list = [1, 2, 3, 4, 5, 6]
# my_list.reverse()
# print(my_list)
#
# # sort()
# my_list = [6, 5, 4, 3, 2, 1]
# my_list.sort()
# print(my_list)
#
# # join()
# my_list = ['HELLO', 'WORLD']
# result = ' ' .join(my_list)
# print(result)
#
# # in
# my_string = "hello"
# print('e' in my_string)
#
# # + (concatenation)
# list1 = [1, 2, 3, 4]
# list2 = [7, 6, 5, 8, 9, 10]
# concatenated_list = list1 + list2
# print(concatenated_list)
#
# # repetition
# my_list = [1, 2]
# repeated_list = my_list * 3
# print(repeated_list)
#
# # extend
# list1 = [1, 2, 3]
# list2 = [4, 5, 6]
# list1.extend(list2)
# print(list1)
#
# # upper(), lower()
# my_string = "HELLO"
# upper_string = my_string.lower()
# print(upper_string)
#
# list1 = [1, 2, 3]
# list2 = [4, 5, 6]
# list3 = [7, 8, 9]
# list1.extend(list2)
# list1.extend(list3)
# print(list1)
#
# # find
# my_string = "HELLO, WORLD"
# index = my_string.find("WORLD")
# print(index)
#
# my_string = "HELLO, WORLD"
# index = my_string.find("WORLD")
# print(index)
#
# # split
# my_string = "HELLO, WORLD"
# parts = my_string.split(" , ")
# print(parts)
#
# # replace (old, new)
#
# my_string = "HELLO , WORLD"
# new_string = my_string.replace("WORLD", "PYTHON")
# print(new_string)
#
#
# # basic slicing
# my_list = [1, 2, 3, 4, 5]
# sliced_list = my_list[1:4]
# print(sliced_list)
#
# # using negative indices
# my_list = [1, 2, 3, 4, 5]
# sliced_list = my_list[-3: -1]
# print(sliced_list)
#
# # slicing with step size
# my_list = [1, 2, 3, 4, 5, 6, 7]
# sliced_list = my_list[::3]
# print(sliced_list)
#
# my_list = [1, 2, 3, 4, 5, 6, 7]
# sliced_list = my_list[0: 7:3]
# print(sliced_list)
#
# # reversing a list
# my_list = [1, 2, 3, 4, 5, ]
# reversed_list = my_list[::-1]
# print(reversed_list)
#
# # omitting indices
# my_list = [1, 2, 3, 4, 5, 6, 7]
# sliced_list = my_list[:6]
# print(sliced_list)
#
# my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9]
# sliced_list = my_list[2:6]
# print(sliced_list)
#
# my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9]
# sliced_list = my_list[-8:-1]
# print(sliced_list)
#
# my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9]
# sliced_list = my_list[-8::-2]
# print(sliced_list)
#
# # >>>>>>>>>>>>>>>>>>>>DICTIONARY>>>>>>>>>>>>>>>>>>>
# # Accessing values
# my_dict = {'name': "samson", 'city': "uyo", 'age': "25"}
# print(my_dict['age'])
#
# # modifying values
# my_dict = {'name': "samson", 'city': "uyo", 'age': "25"}
# my_dict['age'] = 19
# print(my_dict)
#
# # adding new key-value pairs
# my_dict = {'name': "samson", 'city': "uyo", 'age': "25"}
# my_dict['job'] = "developer"
# print(my_dict)
#
# # checking if a key exist
# my_dict = {'name': 'samson'}
# if 'namr' in my_dict:
# print("correct")
# else:
# print("your very wrong")
#
# #removing key-value
# my_dict = {'name': "samson", 'city': "uyo", 'age': "25"}
# del my_dict['city']
# print(my_dict)
#
#
# # >>>>>>>>>>>>>>>>>>>>>>FUNCTIONS IN PYTHON PROGRAMMING>>>>>>>>>>>>>>>
# # string formatting
#
# def greet(name):
# """This function greets the user by name."""
# return f"hello, {name}!"
# print(greet("alice"))
#
# # Basic function
# def greet():
# print("Hello, welcome to python class!")
# greet()
#
# # function with parameters:
# def greet(name):
# print("Hello, "+ name + " ! welcome to python!")
# greet("john")
#
#
# # example2
# def greet(name1,name2):
# print("Hello, " + name1 + " ! welcome to python!" + name2)
# greet("john", "programming")
#
# # function with default parameter:
# def greet(name = 'Guest'):
# print("Hello, " + name +" ! welcome to python!" )
# greet()
# greet("emily")
#
# # Returning values from a function
# def add(a,b):
# return a+b
# result = add(3,5)
# print("the sum is:", result)
#
# # another method
# def add(a,b):
# return a+b
# print("the sum is :", add(3,5))
#
# # recursive function
# def factorial(n):
# if n == 1:
# return 1
# else:
# return n * factorial(n - 1)
# print("factoria of 5:", factorial(5))
#
# # assignment
# def fac_as(p):
# if p == 4:
# return 1
# else:
# return p * fac_as(p - 1)
# print("factoria number:", fac_as(6))
#
#
#
# # python function arguments
# def calculate_area(length, width):
# return length * width
# area_1 = calculate_area(5, 3)
# print(area_1)
#
# def calculate_area(length, width):
# return length * width
# area_2 = calculate_area(width =5, length = 3)
# print(area_2)
#
#
# # defining a default argument
# def greet(name = "world"):
# """"this function greets the user by name"""
# return f"Hello, {name}!"
#
# # calling with defualt argument
# greeting1 = greet()
# greeting2 = greet("Vincent")
# print(f"area 1: {area_1}, area 2: {area_2}")
# print(greeting1, greeting2)
#
# # >>>>>>>>>>>>>>>>>>>positional
arguments>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>.
# def greet (name, message):
# print(f"Hello, {name}! {message}")
# greet("john", "how are you today?")
#
# # >>>>>>>>>>>>>>Keyword argument>>>>>>>>>>>>>>>>.
# def greet (name, message):print(f"Hello, {name}! {message}")
# greet(message = "how are you today?", name = "john")
#
# # >>>>>>>>>>>>default argument>>>>>>>>>>>>>
# def greet (name, message = "how re you doing today "):
# print(f"Hello, {name}! {message}")
# greet("john")
#
# # variable - length positional arguments(*args)
#
# def cal_sum(*args):
# total = sum(args)
# print("sum:",total)
# cal_sum(1, 2, 3, 4, 5,)
#
# # Variable- length Keyword arguments (**Kwargs):
# def print_info(**kwargs):
# for key, value in kwargs.items():
# print(f"{key}: {value}")
# print_info(name = 'john', age = 30, city = 'New Aba')
#
# # >>>>>>>>>>>>>>>>>>>>>>>>> INTRODUCTION TO PYTHON STRINGS
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
#
# # a. using % operator
# name = "john"
# age = 30
# formatted_strings = "my name is %s and i am %d years old."% (name, age)
# print(formatted_strings)
#
# # b. using .format() method:
# name = "jane"
# age = 25
# car = 'volvo'
# city = 'uyo'
#
# form_strings = "my name is {} and i am {} years old, the name of my car is {}, am
from {}..".format(name, age, car, city)
# print(form_strings)
#
# # c. using f-strings (formatted string literals):
# name = "Alice"
# age = 35
# formatted_s = f"my name is {name} and i am {age} years old."
# print(formatted_s)
#
# # d. using str.format() method with named arguments:
# name = "bob"
# age = 40
# f_strings = "my name is {name} and i am {age} years old ." .format(name=name,
age=age)
# print(f_strings)
#
# # E. using template strings
#
# from string import Template
# name = "emily"
# age = 23
# template = Template("my name is $name and i am $age years old.")
# formatted_st = template.substitute(name=name, age=age)
# print(formatted_st)
#
# # >>>>>>>>>>>>>>3. RAW STRINGS >>>>>>>>>>>>>>>>>
# # regular expression
# pattern = r"\d{3}-\d{3}-\d{3}"
# print(pattern)
#
# # file path
# file_path = r"c:\users\john\documents\file.txt"
# print(file_path)
#
# # Escape characters
# raw_strings = r"newline: \n Tab: \t"
# print(raw_strings)
#
# # regular expression replacement
# import re
# text = "Hello, \nworld!"
# pattern = r"\n"
# replacement = r"\\n"
# result = re.sub(pattern, replacement, text)
# print(result)
#
# # JSON DATA
# json_data = r'{"name": "john", "age": 30}'
# print(json_data)
#
#
# import os
# print(os.getcwd())
#
# import re
# pattern = "\d{3}-\d{3}-\d{3}"
# text = "My phone number is 555-123-4567. Call me anytime!"
# match = re.search(pattern, text)
# if match:
# print("Phone number found:", match.group()) # Access the matched text#
# else:
# print("Phone number not found in the text.")
#
# print(pattern)
#
# # listing files in a directiory
# # import os
# # files = os.listdir('.')
# # print(files)
#
# # creating directory
# import os
# #os.mkdir('AMbD')
#
# # to check if the directory you have created exists you do!!!!:
# #if os.path.exists('vincent'):
# # print("yooo men it ezistysfdajnbsanbf")
# #else:
# # print("nah nah it does not")
#
# # changing directory
# import os
# #os.chdir('vincent')
#
# # # Removing a file
# # import os
# # os.remove('vincent')
# #
# # # checking if a file exist
# # import os
# # print(os.path.exists('vincent.txt'))
#
# # CALENDAR MODULE
# # display a calendar
# import calendar
# print(calendar.month(2024, 3))
#
# # checking leap year
# import calendar
# print(calendar.isleap(2024))
#
# # finding the first weekday of a month
# import calendar
# # print(calendar.firstweekday())
#
#
# # >>>>>>>>>>>>>how to get the rest days of the week step 1
# # calendar.setfirstweekday(0)
# second_day_of_the_week = (calendar.firstweekday() + 1)
# print(second_day_of_the_week)
#
# # step 2
# import calendar
# print((calendar.firstweekday() + 1))
#
#
# # determining the number of days in a month
# import calendar
# print(calendar.monthrange(2024, 3))
#
# # formatting dates
# import calendar
# print(calendar.weekday(2024, 3, 16))
#
# # getting current date and time
# import datetime
# c_datetime = datetime.datetime.now()
# print(c_datetime)
#
# # creating a date
# import datetime
# date = datetime.date(2024, 3, 16)
# print(date)
#
# # another method
# import datetime
# date = datetime.date(2024, 3, 16)
# formatted_date = date.strftime('%m/%d/%y')
# print(formatted_date)
#
# # formatting dates
# import datetime
# form_date = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
# print(form_date)
#
# # adding days to a date
# import datetime
# future_date = datetime.datetime.now() + datetime.timedelta(days = 7)
# print(future_date)
#
# # calculating the difference between dates
# import datetime
# date1 = datetime.date(2024, 3, 16)
# date2 = datetime.date(2024, 3, 23)
# difference = date2 - date1
# print(difference.days)
# #
# # # fetching data from a url
# # import urllib.request
# # response = urllib.request.urlopen("http://apexfootball.com")
# # print(response.read())
#
# # handling http errors
#
# import urllib.request
# #import urllib.error
# #try:
# # response = urllib.request.urlopen('http://loctech.ng')
# #except urllib.error.HTTPError as e:
# # print(e.code)
#
# # Making a GET request using request
# #import requests
# #response = requests.get('http://w3school.com', )
# #print(response.json())
# #
# # # making POST request using request
# #
# # import requests
# # data = {'key': 'value'}
# # response = requests.post('http://google.com', data=data)
# # print(response.text)
# #
# # # setting headers in request
# # import requests
# # headers = {'User-agent':'mozilla/5.0'}
# # response = requests.get('http://google.com', headers=headers)
# # print(response.content)
#
# # >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>introduction to oop in python
>>>>>>>>>>>>>>>>>
# class Dog:
# def __init__(self, name, age):
# self.name = name
# self.age = age
# def bark(self):
# return "woof!"
# dog = Dog("Buddy", 3)
# print(dog.bark())
#
# class Student:
# def __init__(self, name, age, school):
# self.name = name
# self.age = age
# self.school = school
# def school():
# return "basic foundation"
# student = Student("alice", 30, 'Basic foundation')
# print( "the name of alice school is: " + student.school)
#
# class Circle:
# def __init__(self, radius):
# self.radius = radius
# def Area(self):
# return 3.14 * self.radius ** 2
# circle = Circle(5)
# print(circle.Area())
#
#
# class Rectangle:
# def __init__(self, length, breadth):
# self.length = length
# self.breadth = breadth
# def Area(self):
# return self.length * self.breadth
# rectangle = Rectangle(5, 8)
# print(rectangle.Area())
#
#
#
#

# example of encapsulation
class Bank_account:
def __int__(self, account_number, balance):
self._account_number = account_number
self._balance = balance
def get_account_number(self):
return self._account_number
def get_balance(self):
return self._balance
def deposit(self, amount):
self._balance += amount
def withdraw(self, amount):
if self._balance >= amount:
self._balance -= amount
else:
print("insufficient funds")

# creating an instance of the class


Account = Bank_account ("123456789" , 1000)

# accessing attributes and methods


print("Account Number:", Account.get_account_number())
print("balance:", Account.get_balance())

Account.deposit(500)
print("balance after deposit:", Account.get_balance())

Account.withdraw(200)
print("Balance after withdrawal:", Account.get_balance())

Account.withdraw(2000)

You might also like