What is Pyhton
Python Is a Coding Language Used by Programers, Hackers, etc, Its The Language That Computers Understand
Note: Python is Not The only Language That Computers Understand
Spacing
Spacing Is Very Important In Python If You Dont Space Your Code Will Fail You Have To Space In Each Command
Put Every Command In a Fresh New Line If Your Using a : Command Then You Should Add a 'TAB' Space
Tab Space is a Space of 4 Lines You Have To Add a Tab Space In Each New Line If You are Using an : Command
" "
" " or ' ' Is Used To Display Text, Here is an example:
"Hello" 'Bye'
print()
print(): is Used To Display Things from The Code, Here is an example:
print("Hello World")
\n
\n: stand for new Line
print("\n[1]iphone\n [2]microwave\n")
Here is How it will look like:
hello
world
Input()
Input() Is Used To Take Input From User, Here is an example:
input("Password")
>>>|
#
# Is a Comment This Will Not Be Read By The Computer only We Can See It, Here is an example:
# This is a Comment
str()
str() str Stand For String This Will Make Anything Strang, Here is an example:
print(str(10))
int()
int() int Stand For Integer This Will Make Anything Integer, Here is an example:
Price = 2
print(int(Price))
exit()
"exit()" is Used To Exit, Here is an example:
exit()
==
"==" is Equal Like If You Want To Say 1 = 1 Computer Understand It 1 == 1, Here is an example:
1 == 1
+
"+" is Add, Here is an example:
1 + 1 == 2
-
"-" is Minus, Here is an example:
3 - 1 == 2
*
"*" is Subtract, Here is an example:
10 * 10 == 100
&&
"&&" Stand For "and" This Will Add Two Commands In one Line, here is an example:
print("Hello") && print("Bye")
if
if: We Use It To Tell The Computer If This Happened Do This, here is an example:
if 1 + 1 == 2:
print("its 2")
else
else Will Be Used After The if Command This Will Make The Computer Understand "if This
Happnned Do This, else do this" here is an example:
if 1 + 1 == 2:
print("Thats Correct")
else:
print("thats Wrong")
elif
elif is a Marge of if And else Its Else And if At The Same Time, here is an example:
name =input("Whats Your Name")
menu = "coffee, Pizza"
if name == ben:
print("hello ben" + menu)
elif name == tom:
print("You Are Not Allowed To Be Here")
exit()
Somthing = Somthing
This Can Be Set Any Thing If You Want Any Thing To Be Anything Just Type Somthing = Somthing like this Price = 15, here is an example:
Price = 0
menu = " [1] Coffee, [2] Tea"
Select = int(input(menu))
if ( Select == 1)
Price = 5
print("coffee Price is " + str(Price))
elif (Select == 2)
Price = 2
print( "Tea price is" + str(Price))
at this example we said Price = 0 that mean the Price is 0 for now
then we said menu = " [1] Coffee, [2] tea" this is our menu
Select = int(input(menu)) Here We are Telling the user to choose from the menu then we make his selection a integer
if ( Select == 1)
Price = 5
print("coffee Price is " + str(Price))
Here we said if the Select is 1 then set the price to be 5 then tell the customer that Coffee Price is the price that we set
elif (Select == 2)
Price = 2
print( "tea price is" + str(Price))
Here we said else if the user selected 2 set the price to be 2 and tell him tea price is the price that we set
Now you are done with basics
i want you to make a store that sells 5 types of coffees and 5 types of tea and each one has a menu
now Lets go a bit Advanced
For
This can be used to loop stuff and more! Here is how it works:
1. Basic Syntax
for variable in sequence:
# Code block to execute
- variable takes the value of each item in sequence one by one
- The loop runs until all items in the sequence are processed.
Example:
numbers = [1, 2, 3]
for num in numbers:
print(num)
Output:
1
2
3
- The loop iterates over the list and prints each element.
2. Iterating Over a List
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
Output:
apple
banana
cherry
- The loop extracts each fruit from the list and prints it.
3. Using range() in a for Loop
The range(start, stop, step)
function generates a sequence of numbers.
for i in range(5): # Starts from 0, stops at 4 (5 is excluded)
print(i)
Output:
0
1
2
3
4
- Loops from 0 to 4 (5 is excluded).
4. Using range() with start and step
for i in range(2, 10, 2): # Starts at 2, stops before 10, increments by 2
print(i)
Output:
2
4
6
8
- The loop starts from 2 and increments by 2 until 10 (exclusive).
5. Iterating Over a String
word = "Python"
for letter in word:
print(letter)
Output:
P
y
t
h
o
n
- Each character in the string is printed one by one.
6. Iterating Over a Dictionary
student_scores = {"Alice": 85, "Bob": 90, "Charlie": 78}
for name, score in student_scores.items():
print(f"{name} scored {score}")
Output:
Alice scored 85
Bob scored 90
Charlie scored 78
- Extracts keys and values, printing them in a formatted manner.
7. Using enumerate() for Index and Value
colors = ["red", "green", "blue"]
for index, color in enumerate(colors):
print(f"Color {index}: {color}")
Output:
Color 0: red
Color 1: green
Color 2: blue
- Uses enumerate() to get both index and value.
8. Nested for Loops
for i in range(1, 4):
for j in range(1, 4):
print(f"({i}, {j})")
Output:
(1, 1)
(1, 2)
(1, 3)
(2, 1)
(2, 2)
(2, 3)
(3, 1)
(3, 2)
(3, 3)
- Loops within loops generate a matrix of values.
9. break and continue
Using break:
for num in range(1, 10):
if num == 5:
break
print(num)
Output:
1
2
3
4
- Stops execution when num reaches 5.
Using continue:
for num in range(1, 6):
if num == 3:
continue
print(num)
Output:
1
2
4
5
- Skips 3 and continues execution.
10. Using else with a for Loop
for num in range(1, 5):
print(num)
else:
print("Loop finished successfully!")
Output:
1
2
3
4
Loop finished successfully!
- The else runs only if the loop completes fully.
11. List Comprehension (Alternative to for Loops)
squares = [x**2 for x in range(1, 6)]
print(squares)
Output:
[1, 4, 9, 16, 25]
- A compact way to generate lists using for loops.
Key Takeaways
- Use for loops to iterate over lists, tuples, strings, dictionaries, and ranges.
- Use break to exit a loop early.
- Use continue to skip an iteration.
- The else clause runs if the loop completes without break.
- enumerate() provides both index and value.
- List comprehensions are a compact alternative.
range()
The range() function is used to generate a sequence of numbers. It is commonly used in loops to iterate over a series of numbers.
1. Basic Syntax
range(start, stop, step)
- start (optional) - The beginning of the sequence (default is 0).
- stop - The end of the sequence (excluded).
- step (optional) - The increment (default is 1).
2. Using range() in a for Loop
for i in range(5): # Starts from 0, stops at 4 (5 is excluded)
print(i)
Output:
0
1
2
3
4
- Loops from 0 to 4 (5 is excluded).
3. Specifying a Start Value
for i in range(2, 6): # Starts from 2, stops at 5
print(i)
Output:
2
3
4
5
- Starts from 2 and stops at 5 (6 is excluded).
4. Using a Step Value
for i in range(1, 10, 2): # Starts at 1, increments by 2, stops before 10
print(i)
Output:
1
3
5
7
9
- Increments by 2 instead of the default 1.
5. Using range() in Reverse
for i in range(10, 0, -2): # Starts at 10, decrements by 2, stops before 0
print(i)
Output:
10
8
6
4
2
- Uses a negative step to count backwards.
6. Converting range() to a List
numbers = list(range(5))
print(numbers)
Output:
[0, 1, 2, 3, 4]
- Converts the sequence into a list.
7. range() with len()
fruits = ["apple", "banana", "cherry"]
for i in range(len(fruits)):
print(f"Index {i}: {fruits[i]}")
Output:
Index 0: apple
Index 1: banana
Index 2: cherry
- Uses range(len(list)) to iterate with an index.
Key Takeaways
- range() generates a sequence of numbers.
- The start parameter is optional (defaults to 0).
- The stop value is always excluded.
- The step allows skipping numbers or counting in reverse.
- Can be converted into a list using list(range()).
import
The import statement in Python is used to bring external modules or built-in modules into the current script, allowing access to their functions and features.
1. Basic Import Syntax
import module_name
- This imports the entire module, and you can access its functions using module_name.function().
2. Importing Specific Functions
from module_name import function_name
- This imports only the specified function, allowing direct use without module prefix.
Example:
from math import sqrt
print(sqrt(25))
Output:
5.0
- Imports only sqrt() from math and uses it directly.
3. Importing with an Alias
import module_name as alias
- This allows renaming the module for shorter references.
Example:
import numpy as np
print(np.array([1, 2, 3]))
Output:
[1 2 3]
- Renames numpy as np for convenience.
4. Importing Everything from a Module
from module_name import *
- This imports all functions and variables from a module but is generally discouraged due to namespace conflicts.
Example:
from math import *
print(sin(0))
Output:
0.0
- Imports all functions from math, allowing direct access.
5. Checking Available Functions in a Module
import module_name
print(dir(module_name))
- Lists all available functions and variables in the imported module.
6. Custom Module Import
import my_module
- You can create your own Python file (my_module.py) and import it like a built-in module.
Key Takeaways
- Use import module_name to load an entire module.
- Use from module_name import function_name to import specific functions.
- Use import module_name as alias to rename a module.
- Use from module_name import * cautiously to avoid conflicts.
- Use dir(module_name) to inspect available functions.
- Custom modules can be imported like built-in modules.
import math
The math module in Python provides mathematical functions that help perform various calculations, including trigonometry, logarithms, factorials, and more.
1. Importing the Math Module
import math
- This imports the built-in math module, allowing access to its functions.
2. Commonly Used Functions
2.1 Square Root
import math
print(math.sqrt(25))
Output:
5.0
- Calculates the square root of a number using math.sqrt().
2.2 Power Function
print(math.pow(2, 3)) # 2 raised to the power of 3
Output:
8.0
- Computes exponentiation using math.pow().
2.3 Factorial
print(math.factorial(5))
Output:
120
- Calculates the factorial of a number using math.factorial().
2.4 Logarithm
print(math.log(100, 10)) # Log base 10
Output:
2.0
- Computes logarithm with a specified base using math.log().
2.5 Trigonometric Functions
print(math.sin(math.radians(30))) # Sine of 30 degrees
Output:
0.5
- Converts degrees to radians and calculates sine using math.sin().
3. Constants
3.1 Value of Pi
print(math.pi)
Output:
3.141592653589793
- Provides the mathematical constant pi.
3.2 Value of Euler’s Number (e)
print(math.e)
Output:
2.718281828459045
- Provides Euler's number e, the base of natural logarithms.
4. Rounding Functions
print(math.ceil(4.3)) # Rounds up
print(math.floor(4.7)) # Rounds down
Output:
5
4
- math.ceil() rounds up to the nearest integer.
- math.floor() rounds down to the nearest integer.
Key Takeaways
- Use import math to access built-in mathematical functions.
- math.sqrt(), math.pow(), and math.factorial() help with calculations.
- Trigonometric functions like math.sin() use radians.
- Constants like math.pi and math.e are useful for precise calculations.
Blog
Trying My Best in cybersecurity, tutorials, and more!