Programming
Programming
s = 'Hi there!'
def check_credentials(username, password): print(len(s))
max_attempts = 3 print(s.center(11))
attempt = 0 print(s.count('e'))
print(s.endswith("there!"))
while attempt < max_attempts:
print(s.startswith("Hi"))
userName = input("Enter your username: ") print(s.find('the'))
userPassword = input("Enter your password: ") print(s.isalpha())
attempt += 1 print(s.lower())
if userName == username and userPassword == print(s.upper())
password: print(s.replace('i','o'))
Writing Numbers to a File
print("login successfully")
import random
return
f = open("integers.txt", 'w')
else: for count in range(500):
print(f"Wrong credentials. you only have: number = random.randint(1,500)
{max_attempts - attempt} attempt") f.write(str(number) + "\n")
print("you reached the maximum attempts. Access f.close()
denied.")
Reading Text from a File
f = open("sample.txt", "r")
check_credentials("jhunel", "123") text = f.read()
print(text)
test File
text = input("Enter your text: ") Reading Numbers from a File
with open("test.txt","a") as file: f = open("integers.txt", 'r')
sum = 0
file.write(text)
for line in f:
file.close()
line = line.strip()
number = int(line)
test File 2(with dynamic function) sum += number
def txt(): print("The sum is: ", sum)
while True:
text = input("enter your message: ") List Methods for Inserting and Removing Elements
file = input("Enter file name: ") Example 1: The program below demonstrates the
para = input("Enter parameter: ") append function.
if para =="a": fruits = ['apple', 'oranges', 'cherries']
print("you selected append") fruits.append('pears')
with open(file, para) as file: print(fruits)
file.write(text)
file.close() Example 2: The program below demonstrates the
elif para = "w": insert function. The element ‘banana’ is inserted
print("you selected write") in index 0.
with open(file, para) as file: fruits = ['apple', 'oranges', 'cherries', 'pears']
file.write(text) fruits.insert(0, 'banana')
file.close() print(fruits)
break
else: Example 3: The program below demonstrates the
print("invalid") pop() function. The last element is remove.
break fruits = ['apple', 'oranges', 'cherries', 'pears']
fruits.pop()
print(fruits)
LIST METHOD
Sorting a List
myList = ['d','e','a','b','h']
myList.sort()
print(myList)
numList = [45,3,23,1,7,89,2]
numList.sort()
print(numList)
Example
def average(list):
sum = 0
for num in list:
sum += num
return sum /len(list)
myList = [1,2,3,4,5]
print(average(myList))
Boolean Functions
def odd(x):
if x % 2 == 1:
return True
else:
return False
n = int(input('Enter an Integer : '))
print(odd(n))