0% found this document useful (0 votes)
74 views

Python 101

The document provides examples of common string, list, and numeric operations in Python including slicing strings, indexing strings, type conversion between strings and integers, using input to get user input, for loops, the len() function, and the enumerate() function. It also discusses built-in string methods like lower(), upper(), count(), find(), replace(), split(), and strip(). Finally, it provides examples of if/else statements and a match statement for pattern matching.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
74 views

Python 101

The document provides examples of common string, list, and numeric operations in Python including slicing strings, indexing strings, type conversion between strings and integers, using input to get user input, for loops, the len() function, and the enumerate() function. It also discusses built-in string methods like lower(), upper(), count(), find(), replace(), split(), and strip(). Finally, it provides examples of if/else statements and a match statement for pattern matching.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 11

1.

Slicing in Python:

text = "Hello, World!"


print(text[0:5]) # Outputs: "Hello"
print(text[7:]) # Outputs: "World!"
print(text[:5]) # Outputs: "Hello"
print(text[:]) # Outputs: "Hello, World!"

2. Indexing with square brackets:

text = "Hello, World!"


print(text[0]) # Outputs: "H"
print(text[7]) # Outputs: "W"

3. Type conversion:

num_str = "123"
num_int = int(num_str)
print(type(num_int)) # Outputs: "<class 'int'>"

num = 123
num_str = str(num)
print(type(num_str)) # Outputs: "<class 'str'>"

4. Input function:

EX1:
name = input("Enter your name: ")
print(f"Hello, {name}!")

EX2:
age = input("Enter your age: ")
print(f"You are {age} years old!")

5. For loop:

for i in range(5):
print(i)
6. Len function

text = "Hello, World!"

print(len(text)) # Outputs: 13

7. Enumerate function:

Python
fruits = ["apple", "banana", "mango"]
for i, fruit in enumerate(fruits):
print(f"Index: {i}, Fruit: {fruit}")

6.2. Manipulating string


(
1. Printing and concatenating strings using the print() and +
functions.
2. Checking if a substring is in a string using the in operator,
which returns True or False.
3. Converting strings to different types using the int(),
float(), and str() functions.
4. Accessing and slicing strings using square brackets and the
colon operator, allows you to get specific characters or
portions of a string.
5. Using the string library, which provides many useful methods
for manipulating strings, such as lower(), upper(), find(),
replace(), strip(), startswith(), and enumerate().
)
1. Printing and concatenating strings using the print() and
+ functions.
>>> a = ‘Hello’
>>> b = a + “ “ + ‘There’
>>> print(b)
Hello There
IN CONCLUSION: When the + operator is applied to strings, it
means concatenation
2. Checking if the substring is in the string using in
operator.
- The in keyword can also be used to check to see if one
string is “in” another string
>>> fruit = “banana”
>>> “n” in fruit
True
- The in expression is a logical expression that returns
TRUE or FALSE and can be used in an IF statement.
>>> if “a” in fruit:
>>> print(“Found it”)
Found it.
3. String library.

Functions Definitio Examples


n
capitalize Coverts print("hello world!".capitalize())
() the first # Outputs: "Hello world!"
character print("PYTHON".capitalize()) #
s in Outputs: "Python"
uppercase
, others
in
lowercase
count() Counts print("banana".count("a")) #
the Outputs: 3
number of print("This is a
occurrenc test.".count("is")) # Outputs: 2
es of a
substring
in the
given
string
lower() Coverts print("Hello, World!".lower()) #
upper() all Outputs: "hello, world!"
uppercase print("PYTHON".lower()) # Outputs:
character "python"
s to
lowercase print("Hello, World!".upper()) #
and vice Outputs: "HELLO, WORLD!"
versa print("python".upper()) # Outputs:
"PYTHON"
format() The print("Hello, {}!".format("World"))
function # Outputs: "Hello, World!"
formats print("{} + {} = {}".format(1, 1,
the given 1+1)) # Outputs: "1 + 1 = 2"
string
into a
nicer
output in
Python
replace() Replaces print("Hello,
a World!".replace("World",
specified "Universe")) # Outputs: "Hello,
phrase Universe!"
with print("banana".replace("a", "A"))
another # Outputs: "bAnAnA"
specified
phrase
Split() Splits a print("Hello, World!".split()) #
string Outputs: ['Hello,', 'World!']
into a print("apple,banana,cherry".split("
list ,")) # Outputs: ['apple',
where 'banana', 'cherry']
each word
is a list
item
Strip() Removes
any
whitespac
e from
the
beginning
or the
end
Len() Returns print(len("Hello, World!")) #
the Outputs: 13
length print(len("")) # Outputs: 0

def main():
x = int(input("what's x? "))
print("x squared is ", square(x))
def square(n):
return n * n
main()

#if statement
x = int(input("What's x? "))
y = int(input("What's y? 4"))
if x < y:
print("x is less than y")
elif x > y:
print("x is more than y")
else:
print("x is equavalent to y")

#if statement
x = int(input("What's x? "))
y = int(input("What's y? 4"))
if x < y or x > y:
print("x is not equal to y")
else:
print("x is equavalent to y")
#if statement
score = int(input("Score: "))
if 90 <= score <= 100:
print("Grade: A")
elif 80 <= score <= 90:
print("Grade: B")
elif 70 <= score <= 80:
print("Grade: C")
elif 60 <= score <= 70:
print("Grade: D")
else:
print("Grade: F")

#learning about case


name = input("what's your name? ")

match name:
case "Harry" | "Herione" | "Ron":
print("Gryffindor")
case "draco":
print("Slytherin")
case _:
print("Who?")

I. Exercises
1. Write a function that takes a list of numbers as input
and returns the maximum number in the list.
def main():
numbers = get_numbers()
maximum = max(numbers)
minimum = min(numbers)
print("The maximum number is:", maximum)
print("The minimum number is:", minimum)

def get_numbers():
numbers = []
while True:
num = input("Enter a number (or 'q'to quit):
")
if num == "q":
break
numbers.append(int(num))
return numbers

main()

Count(start,step) Starts printing


from the “start”
number and prints
infinitely. If
steps are
mentioned, the
numbers are
skipped else step
is 1 by default.
Cycle(iterable) Prints all values
in order from the
passed container.
It restarts
printing from the
beginning again
when all elements
are printed in a
cyclic manner
Repeat(val,num) Repeatedly prints
the passed value
an infinite
number of times
Accumulate(iterable[,func] Returns
accumulated sums
or accumulated
results of other
binary fucntions
Chain(*iterables)
Compress(data,selectors) Filters elements
from data
returning only
those that have a
corresponding
element in
selectors that
evaluates to True
Filterfalse(predicate. Iterable) Returns elements
of iterable for
which predicate
is false
Groupby(iterable[,keyfunc]) Returns
consecutive keys
and groups from
the iterable
Islice(iterable,start,stop[,step]) Returns selected
elements from the
iterable
Takewhile(predicate,iterable) Returns elements
from the iterable
as long as the
predicate is True
Tee(it,n) Returns n
independent
iterators from a
single iterable
Product(*iterbale[,repeat]) Cartesian product
of input iterable
Permutation(iterable[,r]) Returns
successive r-
length
permutations of
elements in the
iterable
Combination(iterable,r) Returns r-length
tuples in sorted
with no repeated
elements
Combination_with_replacement(iterable,r) Returns r-length
tuples in sorted
order with
repeated elements
from itertools import product
a = [1,2]
b = [3]
prod = product(a,b,repeat=2)
print(list(prod))

2. permutation
In Python, a permutation refers to an arrangement of elements. For example, [3, 2, 1] is a
permutation of [1, 2, 3] and vice-versa1.
Python provides a function called permutations in the itertools module to generate all
permutations of a list23. Here is how you can use it:
Python
from itertools import permutations

# Generate all permutations of a list


perm = permutations([1, 2, 3])

# Print each permutation


for i in list(perm):
print(i)

This will output:


(1, 2, 3)
(1, 3, 2)
(2, 1, 3)
(2, 3, 1)
(3, 1, 2)
(3, 2, 1)
Copy

The number of total permutations possible is equal to the factorial of the length (number of
elements). In this case, as we have 3 elements, 3! = 3*2*1 = 64.
You can also generate permutations of a specific length by providing a second argument to
the permutations function3. For example:
Python

This code is AI-generated. Review and use carefully. Visit our FAQ for more information.

Copy
from itertools import permutations

# Generate all permutations of length 2


perm = permutations([1, 2, 3], 2)

# Print each permutation


for i in list(perm):
print(i)

This will output:


(1, 2)
(1, 3)
(2, 1)
(2, 3)
(3, 1)
(3, 2)
from itertools import permutations
rewards = ["gold", "silver", "bronze"]
num_teams = int(input("How many teams joined in? "))
teams = list(range(1, num_teams + 1))
way_to_rewards = permutations(teams, len(rewards))
print(len(list(way_to_rewards)))

#sort using lambda


points2D = [(1,2), (15,1), (5,-1)]

points2D_sorted = sorted(points2D, key= lambda x:


x[1])
print(points2D)
print(points2D_sorted)

#using lambda and filter to get even numbers


a = [1,2,3,4,5,6]
b = filter(lambda x: x%2==0, a)
print(list(b))

c = [x for x in a if x%2==0]
print(c)

You might also like