Python 101
Python 101
Slicing in Python:
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
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}")
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")
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()
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
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
c = [x for x in a if x%2==0]
print(c)