PyhtonBasics S1
PyhtonBasics S1
Variables
Data Types
Casting
I/O in Python
Python Operators
Flow Control
Functions
Object & Class
1. Variables
In [5]:
# Identation
In [6]: x
In [7]:
# ** Comments in Python **
# For multiple comments
"""
this not a comment
But you can use it as so
This is a string but not assigned to a variable so python will ignore it
"""
Out [7]: ' \nthis not a comment \nBut you can use it as so \nThis is a string but not assigned to a variable so python
will ignore it \n'
In [12]:
# Define a variable and assign x a value
x = 1.2 # Dynamically typed
type(x)
2. Types in Python :
Text Type: str
Numeric Types: int, float
Boolean Type: bool
Sequence Types: list, tuple
Mapping Type: dict
Set Types: set
In [14]:
# Sequence types :
# List : Allow duplicates, changeable, ordered, []
languages = ["Swift", "Java", "Python"]
print("Lang 1 : ",languages[0])
# Set : unique values { No duplicates, Not changeable but can add values, Unordered }
f = {"apple", "banana", "cherry", "cherry"}
print("set values : ",f)
# ** You cannot access items in a set by referring to an index or a key. **
Lang 1 : Swift
Product : Xbox 500
Capital City of England : London
set values : {'banana', 'cherry', 'apple'}
In [16]:
# Changing the Value of a Variable in Python
x = 5
In [17]:
x = "Ahmed"
x
In [18]:
# assigning multiple values to multiple variables
x,y,z = 10,20,30
print(" x : " , x , "\n y : " , y , "\n z : " , z)
x : 10
y : 20
z : 30
In [19]:
# assigning same value to multiple variables
x = y = z = 10
print(" x : " , x , "\n y : " , y , "\n z : " , z)
x : 10
y : 10
z : 10
List
In [26]:
#1 Access
l = ["apple", "banana", "cherry"]
print("Our main List : ",l)
print("Access First element : ", l[0])
In [28]:
#2 Add
# At end
l.append("orange")
print("List after adding : ", l)
In [30]:
# At certain position
l.insert(2, "grape")
print("List after adding grape after banana: ", l)
List after adding grape after banana: ['apple', 'banana', 'grape', 'grape', 'cherry', 'orange', 'orange']
In [32]:
#3 Change
l[0] = "Kiwi"
print("List after changing apple to kiwi: ", l)
List after changing apple to kiwi: ['Kiwi', 'banana', 'grape', 'grape', 'cherry', 'orange', 'orange']
In [35]:
List after removing certain value : ['grape', 'grape', 'cherry', 'orange', 'orange']
In [ ]:
In [ ]:
In [36]:
popped element : orange | List after removing last element : ['grape', 'grape', 'cherry', 'orange']
In [37]:
# or remove at certain position
l.pop(0)
print("List after removing first element : ", l)
💥 Assignment : Repeat the previous cell code on Tuple , Dict and Set .
operations : Access,Add, Change, Remove and loop for Tuple , Dict and Set.
In [40]:
integer_number = 123
float_number = 1.23
In [47]:
# explicit
z = '100'
z
In [49]:
z = bool(False)
type(z)
In [46]:
z
In [50]:
print('Python is powerful')
# 1
print('Good Morning!', end= ' ')
print('It is rainy today')
# 2
print('New Year', 2023, 'See you soon!',1, sep= '.')
# 3
Python is powerful
Good Morning! It is rainy today
New Year.2023.See you soon!.1
In [53]:
# Printing strings
# 1. Concatenated strings +
print('Python is ' + 'awesome.')
print("python" + str(1) + "awesome")
# 2. Concatenate using ,
print('Python is ' , 'awesome.')
# used in case of mixing values
print('Python ',3,500 , ' is awesome.')
# 3. OOutput formating
x = 5
y = 10
Python is awesome.
python1awesome
Python is awesome.
Python 3 500 is awesome.
The value of x is 5 and y is 10
Intput
In [55]:
# Get Input
x = input("Enter a value")
Enter a value 5
In [56]:
x # But it's a string !
Enter number 10
In [62]:
type(y)
5. Python Operators
Arithmetic operators : + - / // % *
Assignment Operators : = += -= = /= //= %= *=
Comparison Operators : > , < , != , >= , <=
Logical Operators : and , or , not
Special Operators : Identity operators (is) and memership operators (in)
In [134]:
# Arithmetic operators
a = 4
b = 2
# addition
print ('Sum: ', a + b)
# subtraction
print ('Subtraction: ', a - b)
# multiplication
print ('Multiplication: ', a * b)
# division
print ('Division: ', a / b)
# floor division
print ('Floor Division: ', a // b)
# modulo
print ('Modulo: ', a % b)
# a to the power b
print ('Power: ', a ** b)
Sum: 6
Subtraction: 2
Multiplication: 8
Division: 2.0
Floor Division: 2
Modulo: 0
Power: 16
In [63]:
# Assignment operators
# assign 5 to x
x = 5
x
Out [63]: 5
x /= y # x = x + y
print(x)
0.5
In [137]:
# Comparison Operator
a = 5
b = 2
# equal to operator
print('a == b =', a == b)
In [138]:
# Logical Operator
a = 5
b = 6
print("result : ", (a > 2) and (b >= 6)) # True
# logical AND
print(True and True) # True
print(True and False) # False
# logical OR
print(True or False) # True
# logical NOT
print(not True) # False
result : True
True
False
True
False
True
False
True
False
In [74]:
# Membership Operators
x = 'Hello world'
y = {1:'a', 2:'b'}
True
In [158]:
# check if 'hello' is present in x string
print('hello' not in x) # prints True
True
In [76]:
# check if '1' key is present in y
print(4 in y) # prints True
False
False
1. IF ELSE
In [83]:
# Ex : Positive or negative no
num = int(input("Enter a number : "))
Enter a number : -2
In [81]:
num
Out [81]: 0
In [84]:
if num == 0 :
print("Zero Value.")
elif num > 0 :
print("Number is Positive.")
else:
print("Number is Negative.")
Number is Negative.
In [219]:
# Nested If
# Find max of 3 values entered by user
num1 = int(input("Enter the first number: "))
num2 = int(input("Enter the second number: "))
num3 = int(input("Enter the third number: "))
1. For Loop
In [85]:
# What if we need to print 100 line , rewrite ❌ , use loop ✔
# Example 1
languages = ['Swift', 'Python', 'Go', 'JavaScript']
Swift
Python
Go
JavaScript
In [87]: # Example 2
langs = ['Swift', 'Python', 'Go', 'JavaScript']
Swift
Python
Go
JavaScript
In [88]:
len(langs)
Out [88]: 4
In [89]:
# Example 3 loop over a string chars
for x in 'Python':
print(x)
P
y
t
h
o
n
In [90]:
# Example 4 : If we do not intend to use items of a sequence within the loop, we can write
languages = ['Swift', 'Python', 'Go','1']
for _ in languages:
print('Hi')
Hi
Hi
Hi
Hi
In [91]:
digits = [0, 1, 2]
for i in digits:
print(i)
else:
print("No items left.")
0
1
2
No items left.
In [92]:
# Example 1 : Find sum as long as user enters values or stop on 'exit'
sum = 0
while True:
user_input = input("Enter Number (or 'exit' to stop): ")
Sum = 10
Sum = 50
Enter Number (or 'exit' to stop): abx
Enter Number (or 'exit' to stop): exit
In [96]:
# Example 1 : loop until 5 only
for i in range(10):
if i == 7:
continue # when the loop reaches i=5 it stops
print(i)
0
1
2
3
4
5
6
8
9
In [97]:
# Example 2 : Print only even numbers
# In this case we don't need to stop the whole loop
# we just want to skip odd numbers
for i in range(10):
if i % 2 != 0:
continue # when the loop reaches i=5 it stops
print(i)
0
2
4
6
8
7. Python Functions
Create a function
Call a function
Add Parsmeters (Actual values provided is Arguments. )
Keyword Arguments
Arbitrary Arguments, *args
Arbitrary Keyword Arguments, **kwargs
Default Parameter Value
Passing a List as an Argument
Return Values
Pass Statment (you can pass args or function body)
In [99]:
#1 How to create a function
def print_person():
pass
In [104]:
# How to create a function
def print_person():
print("Hello from func")
In [106]:
#3 Add Parmeters
def print_person(name):
print("Hello ,",name)
In [108]: print_person("Ahmed")
Hello , Ahmed
In [109]:
#4 Keyword Arguments
def print_person(name,age):
print("Hello ,",name, "your age is ", age)
In [110]:
print_person("Amany",age=25)
In [111]:
#5 Default Parameter Value
def print_person(name, age=20):
print("Hello ,", name, "your age is ", age)
In [112]:
print_person("Amany")
In [116]:
print_person("Amany",26 , "Swimming","Drawing","Running")
# You can't add a positional keyword arg followed by arbitary values
Hello : Amany
Your Age: 26
Your hobbies :
Swimming
Drawing
Running
In [117]:
#7 Arbitrary Keyword Arguments, **kwargs {entered as dict}
def print_person(name, age, *hobbies, **other_info):
print("Hello :", name)
print("Your Age:", age)
print("Your hobbies : ")
for hobby in hobbies:
print(hobby)
if other_info:
print("Other Info:")
for key, value in other_info.items():
print("- {}: {}".format(key, value))
Hello : Amany
Your Age: 25
Your hobbies :
Swimming
Drawing
Running
Other Info:
- city: Alex
In [119]:
print_person("Amany", 25, "Swimming","Drawing","Running",country="Eg", city="Alex")
Hello : Amany
Your Age: 25
Your hobbies :
Swimming
Drawing
Running
Other Info:
- country: Eg
- city: Alex
In [121]:
#8 Passing a list as an argument
hobbies = ["Swimming","Drawing","Running"]
Hello : Amany
Your Age: 25
Your hobbies :
Swimming
Drawing
Running
Other Info:
- country: Eg
- city: Alex
Parameters:
name (str): The name of the person.
age (int, optional): The age of the person (default is 0).
*hobbies (str): Any number of hobbies as arbitrary arguments.
**other_info (str, any): Any number of other key-value pairs as arbitrary keyword argu
"""
print("Hello :", name)
print("Your Age:", age)
print("Your hobbies : ")
for hobby in hobbies:
print(hobby)
if other_info:
print("Other Info:")
for key, value in other_info.items():
print("- {}: {}".format(key, value))
In [299]:
print_person.__doc__
Out [299]: '\n This function prints out information about a person, including their name, age, hobbies, and other
information.\n Parameters:\n name (str): The name of the person.\n age (int, optional): The age of the
person (default is 0).\n *hobbies (str): Any number of hobbies as arbitrary arguments.\n **other_info
(str, any): Any number of other key-value pairs as arbitrary keyword arguments.\n '
In [324]:
help(print_person)
Thank You ❤