Converting letters to caps:
Text.Title()
Text is wherever you stored the text, it may be just a text or a
function
For a function:
Parameter (you want convert).title()
Converting list into int, float etc.
str_list = ['1', '2', '3', '4']
int_list = []
for item in str_list:
int_list.append(int(item))
print(int_list)
getting a sum of integer list
int_list = [1, 2, 3, 4]
total = 0
for number in int_list:
total += number
print(total)
While loop
With the while loop we can execute a set of statements as long
as a condition is true.
Example:
Print i as long as i is less than 6:
i=1
while i < 6:
print(i)
i += 1 #can also decrement
i starts at 1, for every value of I, the loop will be executed, until the value
of I exceeds the limit, goes above 6 then the loop will be false. The loop
will stop executing when I gets to 6.
2nd Example:
When using a list, the loop will execute infinitely, pop the list to stop it.
The else Statement
In Python, you can use an else statement with a while loop. The else block
executes after the loop finishes normally (i.e., when the condition
becomes False). However, if the loop is terminated by a break
statement, the else block is skipped.
Normal while loop syntax.
While loop expressions/condition:
statement
Else:
Print()
#Check for an item#
nums = [1, 3, 5, 7]
target = 4
i=0
while i < len(nums):
if nums[i] == target:
print("Found!")
break
i += 1
else:
print("Not found.")
The loop will jump to else because the while loop condition was never
true.That is why it will execute even when there is break but since the
original condition was never true,it won’t even get to “break”.
Break:
The break statement is used to immediately exit a loop, regardless of
whether the loop condition is still True.
i=1
while i < 6:
print(i)
if i == 3:
break
i += 1
Continue:
The continue statement is used to skip the rest of the current loop
iteration and move on to the next one. Skips the specified code item and
print the remaining code.
i=0
while i < 6:
i += 1
if i == 3:
continue
print(i)
let’s say I want to take an input from the user but if the user enters a
certain number the loop will exit. Assign that number to not equal to -1.if
you enter that number the while loop won’t be true anymore and exit to
else. Also repeat the input within the loop for it to be re-entered until the
condition is false:
num=input
while number !=-2:
print number
ask for the number again
else:
gone
As long as the condition is true, the loop will loop. The user controls how
many time the loop is executed.
In While loop you can also set the condition that as long as a condition is
still true,print an output:
Count=0
While True:
Print(x)
Count=count+1
If count==5
break
do exercise:lect 50…23’
Pass in Python
The pass statement is used as a placeholder for future code. When
the pass statement is executed, nothing happens, but you avoid getting
an error when empty code is not allowed.
If x<10:
Pass
print "x" for each letter in a word, here's how you do it:
✅ Example:
word = "hello"
for letter in word:
print("x")
Functions in Python:
A function is a block of code/block of statements which only runs when it
is called. You can pass data, known as parameters, into a function. A
function can return data as a result.
Let’s say you want to execute a code, then execute code x, execute a
code and then execute code x again that’s when we use functions.
In Python a function is defined using the def keyword:
Syntax:
def fun_name(parameters):
function body
return expression(arguments)
Example:
def my_function():
print(“Sandiswa”)
print(“Bhengu”)
#This will not be printed, unless you call the function name. It will be
printed for the number of times it is called, check below.
my_function () --no need to indent. —can call it anywhere.
Arguments
Information can be passed into functions as arguments. Arguments are
specified after the function name, inside the parentheses. You can add as
many arguments as you want, just separate them with a comma.
def my_function(variable/argument):
print(f“my name is {vairable}”)
my_function(“Sandiswa”)
my_fucntion(“Kwanele”)
Output: my name is [Sandiswa]
my name is [Kwanele]
When calling the function, include the vairable to be displayed inside the
brackets—then it will be printed as above.
If two arguments were defined, then even when they’re called on the
function to be printed, there should be two arguments as well.
Positional Arguments
The position in which you put the parameter and the argument matters.
When you call a function, the values you pass are matched to parameters
based on their position/order.
def greet(name, age):
print(f"Hello {name}, you are {age} years old.")
greet("Alice", 25)
Keyword Arguments
You can also send arguments with the key = value syntax.
This way the order of the arguments does not matter.
Do a normal function definition of a function and assign each vairable
when calling the function.
def my_function(child3, child2, child1):
print("The youngest child is " + child3)
my_function (child1 = "Emil", child2 = "Tobias", child3 = "Linus")
Default Parameter Value
The following example shows how to use a default parameter value.
If we call the function without argument, it uses the default value:
def my_function(country = "Norway"):
print("I am from " + country)
my_function("Sweden")
my_function("India")
my_function()
my_function("Brazil")
Arbitrary Arguments, *args
*One defined function(variable/parameter) multiple
(arguments) when called.
If you do not know how many arguments that will be passed into your
function, add * before the parameter name in the function definition. This
way the function will receive a tuple of arguments, and can access the
items accordingly:
For the function to access that specific tuple, it must be specified in the
print [index].
def my_function(*kids):
print("The youngest child is " + kids[2])
my_function("Emil", "Tobias", "Linus")
can also be used to add numbers, if the programmer does not know how
many arguments will be there:
def add(*b):
result=0
for i in b:
result=result+i
return result
print (add(1,2,3,4,5))
#Output:15
print (add(10,20))
#Output:30
Arbitrary Keyword Arguments, **kwargs
If the number of keyword arguments is unknown, add a double ** before
the parameter name:
def my_function(**kid):
print("His last name is " + kid["lname"])
my_function(fname = "Tobias", lname = "Refsnes")
def print_info(**kwargs):
for key, value in kwargs.items():
print(f"{key}: {value}")
print_info(name="Alice", age=30, city="Cape Town")
Output:
name: Alice
age: 30
city: Cape Town
Passing a List as an Argument
To put a letter then shift the letter to get a new letter:
Make if statement for when “encryption” is pressed to execute that
function for “encryption”
That for loop accesses each character, shift it and equate it to the other
one.
Dictionaries in Python
Syntax:
Dictionary_name= {“key”:value,
“Key”:value}
Dictionary_name={“sandiswa”:123, “Kwanele”:234}
To access each:
dictionary_name[“key”]
To change value of the: dictionary_name[“key”] =new value
This does not use index, but key
values can be of any data type int, float, list, tuple
Keys should be immutable
Nested dictionaries
Dictionary_name[“Key”] ={value}
Dictionary_name[“Key”] = {key1:value, key2:value}
Dictionary_name= {key1: {key2:value2}, {key3:value3}}
To access these dictionaries:
Print(dictionary_name[key1][nested key])
The above is to access a nested dictionary, putting the key inside the []
gives you the value of that key.
Strategy: Start from outside then move within, accessing each key in
order to access a certain value.
OR
Get Method:
Dictionary_name.get(key) –case sensitive
Getting a max value in dictionaries:
dict={"sandi":200,"Sya":30}
value=max(dict,key=dict.get)
print(value)
Removing an item:
del dictionary_name[“key”] –if you don’t want to return/print the deleted
value.
When using these methods and you want to
access a nested key/value:
dictionary_name[main_key]…[key x].pop(“key to be discarded”)
dictionary_name.pop(“key”) –if u=you want to return/print the deleted
value.
dictionary_name.popitem(“key”) –delete the last item
dictionary_name.clear() –deletes the entire dictionary, leaves {}
Nested list on dictionaries:
Dictionary_name= {key1: [value1], key2: [value2]}
Access it: dictionary_name[index][key]
Extra Methods:
dictionary_name.key() –displays keys ONLY
dictionary_name.values() –displays values ONLY
dictionary_name.items() –displays ALL items in a form of a tuple ()
dictionary_name2=dictionary_name.copy() –copies the “dictionary.name”
dictionary
Nested dictionaries within a list:
List_name= [{key: value}, {key1: value1}]
For loop and Dictionaries:
for i in dictionary_name:
print(i) –This will print the KEYS of the dictionary
print(dictionary_name[1]) –This will print the VALUES of the dictionary.
for i in dictionary_name.items():
print(i) –This will print the ITEMS of the dictionary (in a tuple form)
Take input data and put it in a dictionary:
for i in range(1,3):
name=input("Enter your name")
amount=int(input("Enter the amount:"))
user_info[name]=amount
print(user_info)
Take input data and put it in a list:
user_list = []
for i in range(1,3):
item = input(f"Enter item : ")
user_list.append(item)
Return in functions:
a return statement is used inside a function to send the result (or output)
of that function back to where the function was called. Think of it as a way
of saying:
👉 “Here’s the answer/output — now take it and use it where I was called.”
Whatever is returned, it is going to be assigned to the called
function. If you return nothing, when you print the function
called, None will be printed.
For example:
Return a,b
Value1,value2=fun()
Print(value1)
Print(value2)
Returning List
We can also return more complex data structures such as lists or
dictionaries from a function:
def fun(n):
return [n**2, n**3]
res = fun(3)
print(res)
Recursion