0% found this document useful (0 votes)
11 views13 pages

PyhtonBasics S1

Uploaded by

aya hamed
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views13 pages

PyhtonBasics S1

Uploaded by

aya hamed
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 13

Pyhton Basics

Variables
Data Types
Casting
I/O in Python
Python Operators
Flow Control
Functions
Object & Class

1. Variables
In [5]:
# Identation

In [6]: x

Out [6]: ' \nhello from \nnultiple line\n'

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)

Out [12]: float

Dynamically typed can infer type from values

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])

# Tuple : Allow duplicates, Not changeable, Ordered, ()


product = ('Xbox', 500,11)
print("Product : ",product[0],product[1])

# Dict : Key , value pairs {NO duplicates, changeable, indexed, Unordered }


capital_city = {'Nepal': 'Kathmandu', 'Italy': 'Rome', 'England': 'London'}
print('Capital City of England : ',capital_city['England'])

# 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

Out [17]: 'Ahmed'

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

Processing Iterables : [Access, Add, Remove, Change, Loop]

List

In [26]:
#1 Access
l = ["apple", "banana", "cherry"]
print("Our main List : ",l)
print("Access First element : ", l[0])

Our main List : ['apple', 'banana', 'cherry']


Access First element : apple

In [28]:

#2 Add
# At end
l.append("orange")
print("List after adding : ", l)

List after adding : ['apple', 'banana', 'cherry', 'orange', 'orange']

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]:

#4 Delete certain value


l.remove("Kiwi")
print("List after removing certain value : ", l)

List after removing certain value : ['grape', 'grape', 'cherry', 'orange', 'orange']

In [ ]:

In [ ]:

In [36]:

# or remove whatever last element


p = l.pop()
print("popped element : ",p," | List after removing last element : ", l)

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)

List after removing first element : ['grape', 'cherry', 'orange']

💥 Assignment : Repeat the previous cell code on Tuple , Dict and Set .
operations : Access,Add, Change, Remove and loop for Tuple , Dict and Set.

3. Casting (Type Conversion )


Implicit Conversion : automatic type conversion
Explicit Conversion : manual type conversion

In [40]:
integer_number = 123
float_number = 1.23

print("Data int number:",type(integer_number))


print("Data float number:",type(float_number))
new_number = integer_number + float_number

# display new value and resulting data type


print("Value:",new_number)
print("\nResulting Data Type:",type(new_number))

Data int number: <class 'int'>


Data float number: <class 'float'>
Value: 124.23

Resulting Data Type: <class 'float'>

In [47]:
# explicit
z = '100'
z

Out [47]: '100'

In [49]:
z = bool(False)
type(z)

Out [49]: bool

In [46]:
z

Out [46]: 100

4. I/O in python (Get User Input)

Output with Print : syntax of the print function accepts 5 parameters

object - value(s) to be printed


sep (optional) - allows us to separate multiple objects inside print().
end (optional) - allows us to add add specific values like new line,tab
file (optional) - where the values are printed. It's default value is sys.stdout (screen)
flush (optional) - boolean specifying if the output is flushed or buffered. Default: False

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

print('The value of x is {} and y is {}'.format(x,y))

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 !

Out [56]: '5'

In [61]: y = int(input("Enter number"))

Enter number 10

In [62]:
type(y)

Out [62]: int

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

In [69]: # assign the sum of x and y to x


x = 1
y = 2

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)

# not equal to operator


print('a != b =', a != b)

# greater than operator


print('a > b =', a > b)

# less than operator


print('a < b =', a < b)

# greater than or equal to operator


print('a >= b =', a >= b)

# less than or equal to operator


print('a <= b =', a <= b)
a == b = False
a != b = True
a > b = True
a < b = False
a >= b = True
a <= b = False

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

In [144]: # Identity operators : is , is not


x1 = 5
y1 = 5
x2 = 'Hello'
y2 = 'Hello'
x3 = [1,2,3]
y3 = [1,2,3]

print(x1 is y1) # prints True


print(x1 is not y1) # prints False

print(x2 is y2) # prints True

print(x3 is y3) # prints False

True
False
True
False

In [74]:
# Membership Operators
x = 'Hello world'
y = {1:'a', 2:'b'}

# check if 'H' is present in x string


print('Hello' in x) # prints True

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

In [165]: # check if 'a' key is present in y


print('a' in y) # prints False

False

6. Python Flow Control


Python if...else : run a block code only when a certain condition is met.
Python for Loop : repeat a block of code.
Python while Loop : Looping
Python break and continue :Stop or continue flow

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: "))

if num1 > num2:


if num1 > num3:
print(num1, "is the maximum number")
else:
print(num3, "is the maximum number")
else:
if num2 > num3:
print(num2, "is the maximum number")
else:
print(num3, "is the maximum number")
Enter the first number: 20
Enter the second number: 10
Enter the third number: 30

30 is the maximum number

1. For Loop

In [85]:
# What if we need to print 100 line , rewrite ❌ , use loop ✔
# Example 1
languages = ['Swift', 'Python', 'Go', 'JavaScript']

# run a loop for each item of the list


for language in languages:
print(language)

Swift
Python
Go
JavaScript

In [87]: # Example 2
langs = ['Swift', 'Python', 'Go', 'JavaScript']

# run a loop for each item of the list


for i in range( len(langs) ):
print( langs[i] )

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

Python for loop with else

In [91]:
digits = [0, 1, 2]

for i in digits:
print(i)
else:
print("No items left.")

0
1
2
No items left.

1. While Loop : ex in case we don't know the number of Iterations

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): ")

if user_input == 'exit' and not(user_input.isnumeric()):


break
if(user_input.isnumeric()):
sum += int(user_input)
print("Sum = ", sum)

Enter Number (or 'exit' to stop): 10

Sum = 10

Enter Number (or 'exit' to stop): 20


Sum = 30

Enter Number (or 'exit' to stop): 20

Sum = 50
Enter Number (or 'exit' to stop): abx
Enter Number (or 'exit' to stop): exit

4. Break and continue

Break : terminate the loop immediately when it is encountered.


Continue : used to skip the current iteration of the loop and the control flow of the program goes to the next iteration

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 [105]: #2 Call a function


print_person()

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)

Hello , Amany your age is 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")

Hello , Amany your age is 20


In [113]:
#6 Arbitrary Arguments (*Args)
def print_person(name, age, *hobbies):
print("Hello :", name)
print("Your Age:", age)
print("Your hobbies : ")
for hobby in hobbies:
print(hobby)

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))

In [118]: print_person("Amany", 25, "Swimming","Drawing","Running", city="Alex")

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"]

print_person("Amany", 25, *hobbies,country="Eg", city="Alex")

Hello : Amany
Your Age: 25
Your hobbies :
Swimming
Drawing
Running
Other Info:
- country: Eg
- city: Alex

What is function is about ?

In [122]: def print_person(name, age=0, *hobbies, **other_info):


"""
This function prints out information about a person, including their name, age, hobbie

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)

Help on function print_person in module __main__:

print_person(name, age=0, *hobbies, **other_info)


This function prints out information about a person, including their name, age, hobbies, and other information.
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 arguments.

Thank You ❤

You might also like