# Phython Learning
https://scrimba.com/
## Why learn python ?
currenlty most popular programming language/skill
versatile, powerful , forgiving and easy to learn
'Made for the web'
Goto language for AI, Machine Learning and Data-Science
## Outputting data and program flow
* Print the message using print command.
* The output will be as per the order we write the code.
Example:
``` print ('Hello World')```
```
print("line1")
print("line2")
print("line10")
print("line3")
````
Output:
```
Hello World!
```
```
line1
line2
line10
line3
```
## Strings, Variables
* everything inside "" is string. here failed_subject is a variable and number 5 is sring.
* belwo example we are trying to print the message using the variable by ``'+ failed_subjects+ '`` variable.
Example :
```
failed_subjects="5"
print('Dear Mrs Badger')
print('Your son Eric is failing ' + failed_subjects + ' subjects.')
print('Eric will need to redo ' + failed_subjects + ' courses.')
print('Eric is doing well in geography.')
```
Output:
```
Dear Mrs Badger
Your son John is failing 2 subjects.
John will need to redo 2 courses.
Eric is doing well in geography.
```
* below example we have another variable called name along with failed_subjects.
*
Example :
```
failed_subjects="2"
name='John'
print('Dear Mrs Badger')
print('Your son ' + name + ' is failing ' + failed_subjects + ' subjects.')
print(name + ' will need to redo ' + failed_subjects + ' courses.')
name="Eric"
print(name + ' is doing well in geography.')
```
Output :
```
Dear Mrs Badger
Your son John is failing 2 subjects.
John will need to redo 2 courses.
Eric is doing well in geography.
```
## Datatypes & Typecasting
interger 2
floating 2.0
Boolean True or False
> Standard in python is to use underscore instead capitailation.
```
is_going_to_party=true
IsGoingToPArty=False
```
> "" '' values seens as a string.
> escaping \ the caractor after \ just see dont interpret.
b='it\'s'
```
print(type('hello'))
print(type(1))
print(type(1.64))
print(type(True))
```
Output :
```
<class 'str'>
<class 'int'>
<class 'float'>
<class 'bool'>
```
### Change the integer to string
Example:
```
failed_subjects=2.56
name='John'
print('Dear Mrs Badger')
print('Your son ' + name + ' is failing ' + str(failed_subjects) + ' subjects.')
print(name + ' will need to redo ' + str(failed_subjects) + ' courses.')
name="Eric"
print(name + ' is doing well in geography.')
```
Output:
```
Dear Mrs Badger
Your son John is failing 2.56 subjects.
John will need to redo 2.56 courses.
Eric is doing well in geography.
```
Example :
```
a = int(1) # a will be 1
b = int(2.5) # b will be 2
c = int("3") # c will be 3
c1 = int(float("3.4")) # c1 will be...
d = float(1) # d will be 1.0
e = float(2.5) # e will be 2.5
f = float("3") # f will be 3.0
g = float("4.23") # g will be 4.23
h = str("80s") # h will be '80s'
i = str(22) # i will be '22'
j = str(3.01) # j will be '3.01'
print([a,b,c,d,e,f,g,h,i,j])
```
Output:
```
[1, 2, 3, 1.0, 2.5, 3.0, 4.23, '80s', '22', '3.01']
```
## Variables & Datatypes Exercise
### print('Variables & Datatypes - Exercise')
Example:
```
#Create appropriate Variables for Item name, the price
#and how many you have in stock
item_name = 'widget'
price = 23.5
inventory = 100
is_in_inventory = True
print(item_name, price, inventory)
```
Output:
```
Variables & Datatypes - Exercise
widget 23.5 100
```
## Arithmetic operations
Basic Arithmetic
Addition : 12
Subtraction : 8
Multiplication : 20
Division (float) : 5.0
Division (floor) : 5
Modulus : 0
Exponent : 100
## Strings-Basics/Slicing
Example:
```
msg='welcome to Python 101: Strings'
print(msg,msg)
print(msg.upper())
print(msg.lower())
print(msg.capitalize())
print(msg.title())
print(len(msg))
print(msg.count('o'))
print(msg[2])
print(msg[2:7])
```
Output:
```
welcome to Python 101: Strings welcome to Python 101: Strings
WELCOME TO PYTHON 101: STRINGS
welcome to python 101: strings
Welcome to python 101: strings
Welcome To Python 101: Strings
30
3
l
lcome
```
## Exercise-String-Basics/Slicing
#### Exercise
1. From the string "Welcome to Python 101: Strings", extract text and create print a new string that says
* "1 Welcome Ring To Tyler"
* Every first letter in a word should be capitalized (title format)
2. print the same string backwards...
```
msg='welcome to Python 101: Strings'
msg1=msg[18]+' '+msg[:8]+msg[25:29]+msg[7:11]+msg[13]+msg[12]+msg[2]+msg[1]+msg[-5]
print(msg1.title())
print(msg1[::-1].title())
```
Ouput:
```
1 Welcome Ring To Tyler
Relyt Ot Gnir Emoclew 1
```
## String-2 Find/replace,sring formatting
* to get multi line string use """ break the line and end with """
```
msg="""hellow
how are you
who are you """
print(msg)
`````
Output:
```
hellow
how are you
who are you
```
* find the character
```
msg='Welcome to Python 101: Strings'
print(msg.find('Python'))
print(msg.find('h'))
```
Output:
```
11
7
```
* replace the string
```
msg='Welcome to Python 101: Strings'
print(msg.replace('Python','Linux'))
```
Output:
```
Welcome to Linux 101: Strings
```
* membership, check if the string is present or not
```
msg='Welcome to Python 101: Strings'
print('Python' not in msg)
print('Python' in msg)
```
Output:
```
False
True
```
### string formatting
* format string terry inside the [] and second capitalize terry.
name='TERRY'
color = 'RED'
msg = '[' + name + '] loves the color ' + color + '!'
msg1 = f'[{name}] loves the color {color.lower()}!'
msg2 = f'[{name.capitalize()}] loves the color {color.lower()}!'
print(msg)
print(msg1)
print(msg2)
[TERRY] loves the color RED!
[TERRY] loves the color red!
[Terry] loves the color red!
## User Input
name= input('What is your name?:')
age=input('What is your age?:')
print('Hello '+ name + '! you are '+ age + 'Years old.')
Output:
What is your name?:suresh
What is your age?:31
Hello suresh! you are 31Years old.
num1=input('Enter a digit: ')
num2=input('Enter a second number:')
answer=float(num1)+float(num2)
print(answer)
Output:
Enter a digit: 12
Enter a second number:34
46.0
### USer Input -Exercise
take input from user
their first name and distance in km
Print
Greet user by name and show km, and mile values
1 mile is 1.609 kilometers
```
# - Create a distance converter converting Km to miles
# - Take two inputs from user: Their first name and the distance in km
# - Print: Greet user by name and show km, and mile values
# - 1 mile is 1.609 kilometers
# - hint: use correct types for calculating and print
# - Did you capitalize the name
name=input('Enter your name')
distance_km= input('Enter distance in km: ')
distance_mi = float(distance_km)/1.609
print(f'Hi {name.title()}! {distance_km}km is equivalent to {round(distance_mi,1)} miles.')
```
Output:
Enter your name Suresh
Enter distance in km: 6
Hi Suresh ! 6km is equivalent to 3.7 miles.
## Lists - Basics
List is similar to variable and an list can hold multiple instaces.
friends = ['John','Michael','Terry','Eric','Graham']
print(friends[1],friends[4])
print(len(friends))
print(friends[:])
print(friends[0:2])
print(friends.index('Eric'))
Output:
Michael Graham
5
['John', 'Michael', 'Terry', 'Eric', 'Graham']
['John', 'Michael']
3
### List options
```
[snandago@sureshn ~]$ python
Python 3.7.6 (default, Jan 30 2020, 09:44:41)
[GCC 9.2.1 20190827 (Red Hat 9.2.1-1)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> friends = ['John','Michael','Terry','Eric','Graham']
>>> cars =[911,130,328,535,740,308]
>>> print(friends)
['John', 'Michael', 'Terry', 'Eric', 'Graham']
>>> friends.sort()
>>> print(friends)
['Eric', 'Graham', 'John', 'Michael', 'Terry']
>>> friends.sort(reverse=True)
>>> print(friends)
['Terry', 'Michael', 'John', 'Graham', 'Eric']
>>> friends.reverse()
>>> print(friends)
['Eric', 'Graham', 'John', 'Michael', 'Terry']
>>> print(sum(cars))
2952
>>> print(min(cars))
130
>>> friends.append('terry6')
>>> print(friends)
['Eric', 'Graham', 'John', 'Michael', 'Terry', 'terry6']
>>> friends[2]='suresh'
>>> print(friends)
['Eric', 'Graham', 'suresh', 'Michael', 'Terry', 'terry6']
>>> friends.extend(cars)
>>> print(friends)
['Eric', 'Graham', 'suresh', 'Michael', 'Terry', 'terry6', 911, 130, 328, 535, 740, 308]
>>> friends.remove('Terry')
>>> print(friends)
['Eric', 'Graham', 'suresh', 'Michael', 'terry6', 911, 130, 328, 535, 740, 308]
>>> friends.pop()
308
>>> print(friends)
['Eric', 'Graham', 'suresh', 'Michael', 'terry6', 911, 130, 328, 535, 740]
>>> friends.clear()
>>> print(friends)
[]
>>> friends = ['John','Michael','Terry','Eric','Graham']
>>> del friends[2]
>>> print(friends)
['John', 'Michael', 'Eric', 'Graham']
>>>
[snandago@sureshn ~]$ python
Python 3.7.6 (default, Jan 30 2020, 09:44:41)
[GCC 9.2.1 20190827 (Red Hat 9.2.1-1)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> friends = ['John','Michael','Terry','Eric','Graham']
>>> new_friends=friends[:]
>>> print(new_friends)
['John', 'Michael', 'Terry', 'Eric', 'Graham']
>>> new_friends1=friends.copy()
>>> print(new_friends1)
['John', 'Michael', 'Terry', 'Eric', 'Graham']
>>> new_friends2=list(friends)
>>> print(new_friends2)
['John', 'Michael', 'Terry', 'Eric', 'Graham']
>>>
```
### List - Exercise
Selling Lemonade
- You sell Lemonade over two weeks, the lists show number of lemonades sold per week.
- profit for each lemonde sold is 1.5$
- Add another day to week 2 list by capturing a number as input
- Combine the two lists into the list called 'sales'
- Calculate/Print how much you have earned on Best Dat, Worst Day, separatetly and in total
```
sales_w1 = [7,3,42,19,15,35,9]
sales_w2 = [12,4,26,10,7,28]
sales = []
new_day= input('Enter #of lemonades for new day: ')
sales_w2.append(int(new_day))
#sales.extend(sales_w1)
#sales.extend(sales_w2)
sales= sales_w1 + sales_w2
sales.sort()
worst_day_prof = min(sales) * 1.5
best_day_prof = max (sales) * 1.5
print(f'Worst day profit:$ {worst_day_prof}')
print(f'Best day profit:$ {best_day_prof}')
print(f'Combined profit:$ {worst_day_prof + best_day_prof}')
````
Output:
```
Enter #of lemonades for new day: 10
Worst day profit:$ 4.5
Best day profit:$ 63.0
Combined profit:$ 67.5
````
## Split and Join
> split the string and created a list
```
msg ='Welcome to Python 101: Split and Join'
csv = 'Eric,John,Michael,Terry,Graham'
friends_list = ['Eric','John','Michael','Terry','Graham']
print(msg.split())
print(msg.split(' '))
print(msg.split(','), type(msg.split(' ')))
print(str(friends_list))
print('-'.join(friends_list))
print(''.join(msg.split()))
print(msg.replace(' ',''))
```
Output:
```
['Welcome', 'to', 'Python', '101:', 'Split', 'and', 'Join']
['Welcome', 'to', 'Python', '101:', 'Split', 'and', 'Join']
['Welcome to Python 101: Split and Join'] <class 'list'>
['Eric', 'John', 'Michael', 'Terry', 'Graham']
Eric-John-Michael-Terry-Graham
WelcometoPython101:SplitandJoin
WelcometoPython101:SplitandJoin
```
## Split and Join - Exercise
```
csv = 'Eric,John,Michael,Terry,Graham:TerryG;Brian'
print(csv.split(','))
print(','.join(csv.split(';')))
print(','.join(csv.split(';')).split(':'))
print(','.join(','.join(csv.split(';')).split(':')))
print((','.join(','.join(csv.split(';')).split(':'))).split(','))
friends_list = (','.join(','.join(csv.split(';')).split(':'))).split(',')
print(friends_list)
print('replace', csv.replace(';',',').replace(':',',').split(','))
```
```
['Eric', 'John', 'Michael', 'Terry', 'Graham:TerryG;Brian']
Eric,John,Michael,Terry,Graham:TerryG,Brian
['Eric,John,Michael,Terry,Graham', 'TerryG,Brian']
Eric,John,Michael,Terry,Graham,TerryG,Brian
['Eric', 'John', 'Michael', 'Terry', 'Graham', 'TerryG', 'Brian']
['Eric', 'John', 'Michael', 'Terry', 'Graham', 'TerryG', 'Brian']
replace ['Eric', 'John', 'Michael', 'Terry', 'Graham', 'TerryG', 'Brian']
```
## Tuples
Tuples is actualy a list
change is immutable
less complex and faster then regular list
tupes use pranthathises
```
#Tuples - faster Lists you can't change
friends = ['John','Michael','Terry','Eric','Graham']
friends_tuple = ('John','Michael','Terry','Eric','Graham')
print(friends)
print(friends_tuple)
print(friends_tuple[2:4])
```
```
['John', 'Michael', 'Terry', 'Eric', 'Graham']
('John', 'Michael', 'Terry', 'Eric', 'Graham')
('Terry', 'Eric')
```
## Sets
sets use curly bracket ,
main difference between list and sets is that sets is un ordered and remove any duplicate.
very fast.
```
#Sets - blazingly fast unordered Lists
friends = ['John','Michael','Terry','Eric','Graham']
friends_tuple = ('John','Michael','Terry','Eric','Graham')
friends_set = {'John','Michael','Terry','Eric','Graham','Eric'}
my_friends_set = {'Reg','Loretta','Colin','Eric','Graham'}
print(friends_set.intersection(my_friends_set))
print(friends_set.difference(my_friends_set))
print(friends_set.union(my_friends_set))
```
```
{'Graham', 'Eric'}
{'John', 'Terry', 'Michael'}
{'Loretta', 'John', 'Michael', 'Eric', 'Colin', 'Terry', 'Graham', 'Reg'}
```
#Sets - blazingly fast unordered Lists
#empty Lists
empty_list = []
empyt_list = list()
#empty Tuple
empty_tuple = ()
empty_tuple = tuple()
#empty Set
empty_set = {} # this is wrong, this is a dictionary
empty_set = set()
## Sets - Exercise
```
#Sets - Exercise
#1. Check if ‘Eric’ and ‘John’ exist in friends
#2. combine or add the two sets
#3. Find names that are in both sets
#4. find names that are only in friends
#5. Show only the names who only appear in one of the lists
#6. Create a new cars-list without duplicates
friends = {'John','Michael','Terry','Eric','Graham'}
my_friends = {'Reg','Loretta','Colin','John','Graham'}
cars =['900','420','V70','911','996','V90','911','911','S','328','900']
print('Eric' in friends and 'John' in friends)
print(friends.union(my_friends))
print(friends | my_friends)
print(friends.intersection(my_friends))
print (friends & my_friends)
print(friends.difference(my_friends))
print(my_friends.symmetric_difference(friends))
print(my_friends - friends)
cars_no_dupl = set(cars)
print (cars_no_dupl)
cars_no_dupl =list(set(cars))
print(cars_no_dupl)
```
```
True
{'John', 'Eric', 'Graham', 'Michael', 'Colin', 'Reg', 'Loretta', 'Terry'}
{'John', 'Eric', 'Graham', 'Michael', 'Colin', 'Reg', 'Loretta', 'Terry'}
{'John', 'Graham'}
{'John', 'Graham'}
{'Eric', 'Terry', 'Michael'}
{'Colin', 'Eric', 'Reg', 'Loretta', 'Terry', 'Michael'}
{'Reg', 'Loretta', 'Colin'}
{'328', '911', '996', 'V70', 'S', 'V90', '420', '900'}
['328', '911', '996', 'V70', 'S', 'V90', '420', '900']
```
## Comments
text in the code python ignore
1. Ready notes to other person
2. Debug/testing
3. Auto generate documentation of the code.
```
print("#Comments")
#Hiding in the comments
#more comments
```
## Functions - Calling, Parameters,Argument,Defaults
Function is way to bundle the code you often use can be reused later.
`def is used to define the functon
1. Allow to split up the code.
2. Always use name you understand.
3. Always declare the fuction before you use the function.
```
def greeting(name):
print("Hello " + name + "!")
greeting("Suresh")
def greeting1(name,age=28):
print("Hello " + name + ",you are " + str(age) + "!")
print(f"Hello {name}, you are {age}!")
greeting1("suresh","31")
greeting1("Jim")
name = input ("Enter your name: ")
greeting1(name,32)
greeting1("jim")
```
```
Hello Suresh!
Hello suresh,you are 31!
Hello suresh, you are 31!
Hello Jim,you are 28!
Hello Jim, you are 28!
Enter your name: James
Hello James ,you are 32!
Hello James , you are 32!
Hello jim,you are 28!
Hello jim, you are 28!
```
## Functions - Named Notation
In named notation, the arguments are matched to the function parameters by name and can be written in any order.
```
def greeting(name, age=28, color="red"):
#Greets user with “name” from “input box” and “age”, if unavailable, default age is used
print(f"Hello {name.capitalize()}, you will be {age+1} next birthday!")
print(f"We hear you like the color {color.lower()}!")
greeting(age=27, name="brian", color="Blue")
```
```
Hello Brian, you will be 28 next birthday!
We hear you like the color blue!
```
## Function - Exercise
1. Add new print statement - on a new line
which says 'We hear you like the color xxx! xxx is a string with color
2. extend the function with another input parameter 'color', that defaults to 'red'
3. Capture the color via an input box as variable:color
4. Change the 'You are xx!' text to say 'you will be xx+1 years old next birthday adding 1 to the age
5. Capitalize first letter of the 'name', and rest are small caps
6. Favorite color should be in lowercase
```
def greeting(name, age=28, color = 'red'):
#Greets user with 'name' from 'input box' and 'age', if available, default age is used
print('Hello ' + name.capitalize() + ', you will be ' + str(age+1) +' next birthday!')
print(f'Hello {name.capitalize()}, you will be {age+1} next birthday!')
print(f'We hear you like the color {color.lower()}!')
name = input('Enter your name: ')
age = input('Enter your age: ')
color = input('Enter favorite color: ')
greeting(name, int(age), color)
```
```
Enter your name: Suresh
Enter your age: 23
Enter favorite color: White
Hello Suresh , you will be 24 next birthday!
Hello Suresh , you will be 24 next birthday!
We hear you like the color white!
```
## Return Statements
Some time we need the function to give data/ value back that is return statements.
```
def value_added_tax(amount):
tax = amount * 0.25
total_amount = amount * 1.25
return tax
price = value_added_tax(100)
print(price,type(price))
```
```
25.0 <class 'float'>
```
```
def value_added_tax(amount):
tax = amount * 0.25
total_amount = amount * 1.25
return tax, amount, total_amount
price = value_added_tax(100)
print(price,type(price))
```
```
(25.0, 100, 125.0) <class 'tuple'>
```
def value_added_tax(amount):
tax = amount * 0.25
total_amount = amount * 1.25
return [tax, amount, total_amount]
price = value_added_tax(100)
print(price[1],type(price))
[25.0, 100, 125.0] <class 'list'>
100 <class 'list'>
```
def value_added_tax(amount):
tax = amount * 0.25
total_amount = amount * 1.25
return {tax, amount, total_amount}
price = value_added_tax(100)
print(price,type(price))
```
```
{25.0, 100, 125.0} <class 'set'>
```
```
def value_added_tax(amount):
tax = amount * 0.25
total_amount = amount * 1.25
return f"{tax}, {amount}, {total_amount}"
price = value_added_tax(100)
print(price,type(price))
```
```
25.0, 100, 125.0 <class 'str'>
```
## Coparisons and Booleans
Operator
```
a = 7
b = 3
#Operator
print(a == b)
print(a != b)
print(a > b)
print (a< b)
print (a <= b)
print (a >= b)
print('o' in 'john')
print('o'not in 'john')
```
```
False
True
True
False
False
True
True
False
```
```
a = [3,7,42]
b = [3,7,42]
print(a == b)
print(a is b)
print(id(a), id(b))
```
```
True
False
140456096768560 140456096771120
```
```
a=7
b=3
print('a == b is', a == b)
print('a != b is', a != b)
print('a > b is', a > b)
print('a < b is', a < b)
print('a >= b is', a >= b)
print('a <= b is', a <= b)
print('o in John is ','o' in 'John') #membership
print('o in John is ','o' not in 'John') #non membership
print('John is John ','John' is 'John') #identity
print('John is not John is ','John' is not 'John') # negative identity
```
```
a == b is False
a != b is True
a > b is True
a < b is False
a >= b is True
a <= b is False
o in John is True
o in John is False
John is John True
John is not John is False
```
```
#!/usr/bin/python
print(int(False))
print(bool('parrot'))
print(bool('p'))
print(bool(''))
print(bool(' '))
print(bool(42))
print(bool(1))
print(bool(0))
print(bool([1,2]))
print(bool([]))
print(42 + True)
print(42 + False)
```
```
0
True
True
False
True
True
True
False
True
False
43
42
```
## Conditionals; If, Else, Elif
This will help in make the programs take decisions.
```
is_raining = True
is_cold = True
print ("Good Morning")
if is_raining and is_cold:
print("bring Umbrella and jacket or both")
elif is_raining and not(is_cold):
print("Bring Unbrella")
elif not(is_raining) and is_cold:
print("Bring jacker")
else:
print("Umbrella is optional")
```
```
Good Morning
bring Umbrella and jacket or both
```
```
amount = 51
if amount <= 50:
print("purchase approved")
else:
print("Please enter your pin!")
```
```
[snandago@sureshn Chap01]$ /usr/bin/python "/home/snandago/learning/Ex_Files_Python_EssT/Exercise Files/Chap01/su.py"
purchase approved
[snandago@sureshn Chap01]$ /usr/bin/python "/home/snandago/learning/Ex_Files_Python_EssT/Exercise Files/Chap01/su.py"
Please enter your pin!
[snandago@sureshn Chap01]$
```
## If/Elif/Else - Exercise
> Create a calculator which handles +,-,*,/ and outputs answer based on the mode/ operator used
> Hint: use 3 separate inputs
> Bonus: Extend functionality with extra mode so it also does celsius to fahrenheit conversion
> formula is: temp in C*9/5 + 32 = temp in f
```
mode = input('Enter math operation(+,-,*,/) or f for Celsius to Fahrenheit conversion: ')
num1 = float(input('Enter first number: '))
if mode.lower() == 'f':
print(f'{num1} Celsius is equivalent to {(num1*9/5)+32 } fahrenheit')
else:
num2 = float(input('Enter second number: '))
if mode == '+':
print(f'Answer is: {num1 + num2}')
elif mode == '-':
print(f'Answer is: {num1 - num2}')
elif mode == '*':
print(f'Answer is: {num1 * num2}')
elif mode == '/':
print(f'Answer is: {num1 / num2}')
else:
print('Input error!')
```
Output:
```
[snandago@sureshn Exercise Files]$ /usr/bin/python "/home/snandago/learning/Ex_Files_Python_EssT/Exercise Files/Chap01/su.py"
Enter math operation(+,-,*,/) or f for Celsius to Fahrenheit conversion: +
Enter first number: 10
Enter second number: 25
Answer is: 35.0
[snandago@sureshn Exercise Files]$ /usr/bin/python "/home/snandago/learning/Ex_Files_Python_EssT/Exercise Files/Chap01/su.py"
Enter math operation(+,-,*,/) or f for Celsius to Fahrenheit conversion: f
Enter first number: 32
32.0 Celsius is equivalent to 89.6 fahrenheit
[snandago@sureshn Exercise Files]$
```
## Conditionals -Exercise improve
* optimize/shorten the code in the function
* try to reduce the number of conditionals
```
def num_days(month):
if month == 'jan' or month == 'mar' or month == 'may' or month == 'jul' or month == 'aug' or month == 'oct' or month == 'dec':
print('number of days in',month,'is',31)
elif month == 'feb':
print('number of days in',month,'is',28)
elif month == 'apr' or month == 'jun' or month == 'sep' or month == 'nov':
print('number of days in',month,'is',30)
num_days('jul')
```
```
[snandago@sureshn Exercise Files]$ /usr/bin/python "/home/snandago/learning/Ex_Files
_Python_EssT/Exercise Files/Chap01/su.py"
number of days in jul is 31
[snandago@sureshn Exercise Files]$
```
```
def num_days(month):
days = 31
if month == 'apr' or month =='jun' or month =='sep' or month =='nov':
days = 30
elif month == 'feb':
days = 28
print('number of days in',month,'is',days)
num_days('feb')
```
```
[snandago@sureshn Exercise Files]$ /usr/bin/python "/home/snandago/learning/Ex_Files
_Python_EssT/Exercise Files/Chap01/su.py"
number of days in feb is 28
[snandago@sureshn Exercise Files]$
```
```
def num_days(month):
days = 31
if month in {'apr','jun','sep','nov'}:
#if month == 'apr' or month =='jun' or month =='sep' or month =='nov':
days = 30
elif month == 'feb':
days = 28
print('number of days in',month,'is',days)
num_days('jan')
```
```
[snandago@sureshn Exercise Files]$ /usr/bin/python "/home/snandago/learning/Ex_Files
_Python_EssT/Exercise Files/Chap01/su.py"
number of days in jan is 31
[snandago@sureshn Exercise Files]$
```
## While loops
loops will run again and again until we say to stop.
* Three Loop Questions:
* What do I want to repeat?
* What do I want to change each time?
* How long should we repeat?
*
```
print("1.*Loops are great*")
print("2.**Loops are great**")
print("3.***Loops are great***")
print("4.****Loops are great****")
print("5.*****Loops are great*****")
i=0
while i < 5:
i=i+1
print(f"{i}."+ "*"*i + "Loops are awesome" + "*"*i)
```
```
Python_EssT/Exercise Files/Chap01/su.py"
1.*Loops are great*
2.**Loops are great**
3.***Loops are great***
4.****Loops are great****
5.*****Loops are great*****
1.*Loops are awesome*
2.**Loops are awesome**
3.***Loops are awesome***
4.****Loops are awesome****
5.*****Loops are awesome*****
[snandago@sureshn Exercise Files]$
```
### While loops - Exercise
* Guess the correct number in 3 guesses. If you don’t get it right after 3 guesses you lose the game.
* Give user input box: 1. To capture guesses,
* print(and input boxes) 1. If user wins 2. If user loses
* Tip:( remember you won’t see print statements durng execution, so If you want to see prints during whle loop, then print to the input box
* Modification 1: number 1-100, tell user if guess is too high/low ,and let them have 5-10 guesses.
* Tip:( remember you won’t see print statements during execution, so If you want to see prints during whle loop, print to the input box (This is specific to this platform)
```
print('Guessing game')
num = 12
guess = 0
guess_limit= 4
guess_number = 0
guess = int(input(f'Guess a number 1-20: '))
while guess_number < guess_limit:
if guess != num:
guess_number +=1
if guess > num:
guess = int(input(f'{guess} Too high - Guess again 1-100: '))
else:
guess = int(input(f'{guess} too low - Guess again 1-100: '))
if guess == num:
print(f'You Win! You Guessed it: {guess}')
break
if guess != num:
print(f'Sorry you lose! It was {num}')
```
```
[snandago@sureshn Exercise Files]$ /usr/bin/python "/home/snandago/learning/Ex_Files
_Python_EssT/Exercise Files/Chap01/su.py"
Guessing game
Guess a number 1-20: 2
2 too low - Guess again 1-100: 1
1 too low - Guess again 1-100: 2
2 too low - Guess again 1-100: 3
3 too low - Guess again 1-100: 4
Sorry you lose! It was 12
[snandago@sureshn Exercise Files]$
[snandago@sureshn Exercise Files]$ /usr/bin/python "/home/snandago/learning/Ex_Files
_Python_EssT/Exercise Files/Chap01/su.py"
Guessing game
Guess a number 1-20: 12
You Win! You Guessed it: 12
[snandago@sureshn Exercise Files]$
```
### For loops and nesting
* looping through all the letters memeber string list all
```
friends = ['John','Terry','Eric','Michael','George']
for friend in friends:
print(friend)
print("For Loop done!")
```
```
[snandago@sureshn Exercise Files]$ /usr/bin/python "/home/snandago/learning/Ex_Files
_Python_EssT/Exercise Files/Chap01/su.py"
John
Terry
Eric
Michael
George
For Loop done!
[snandago@sureshn Exercise Files]$
```
```
for letter in 'Norwegian blue':
print(letter)
print("For Loop done!")
```
```
[snandago@sureshn Chap01]$ /usr/bin/python "/home/snandago/learning/Ex_Files_Python_EssT/Exercise Files/Chap01/suresh.py"
N
o
r
w
e
g
i
a
n
b
l
u
e
For Loop done!
[snandago@sureshn Chap01]$
```
```
for furgle in range (2,8):
print(furgle)
print("For Loop done!")
```
```
[snandago@sureshn Chap01]$ /usr/bin/python "/home/snandago/learning/Ex_Files_Python_EssT/Exercise Files/Chap01/suresh.py"
2
3
4
5
6
7
For Loop done!
[snandago@sureshn Chap01]$
```
```
for name in ['john','Terry','Eric','Michael','George']:
print(name)
print("For Loop done!")
```
```
[snandago@sureshn Chap01]$ /usr/bin/python "/home/snandago/learning/Ex_Files_Python_
EssT/Exercise Files/Chap01/suresh.py"
john
Terry
Eric
Michael
George
For Loop done!
[snandago@sureshn Chap01]$
```
```
friends = ['john','Terry','Eric','Michael','George']
for friend in friends:
print(friend)
print("For Loop done!")
```
```[snandago@sureshn Chap01]$ /usr/bin/python "/home/snandago/learning/Ex_Files_Python_
EssT/Exercise Files/Chap01/suresh.py"
john
Terry
Eric
Michael
George
For Loop done!
[snandago@sureshn Chap01]$
````
```
friends = ['john','Terry','Eric','Michael','George']
for index in range(len(friends)):
print(friends[index])
print("For Loop done!")
```
```
[snandago@sureshn Chap01]$ /usr/bin/python "/home/snandago/learning/Ex_Files_Python_
EssT/Exercise Files/Chap01/suresh.py"
john
Terry
Eric
Michael
George
For Loop done!
[snandago@sureshn Chap01]$
```
```
friends = ['john','Terry','Eric','Michael','George']
for friend in friends:
if friend == 'Eric':
print('Found' + friend + '!')
continue
print(friend)
print("For Loop done!")
```
```
[snandago@sureshn Chap01]$ /usr/bin/python "/home/snandago/learning/Ex_Files_Python_
EssT/Exercise Files/Chap01/suresh.py"
john
Terry
FoundEric!
Michael
George
For Loop done!
[snandago@sureshn Chap01]$
```
Nested loop
```
friends = ['john','Terry','Eric']
for friend in friends:
for number in [1,2,3]:
print(friend, number)
print("For Loop done!")
```
```
EssT/Exercise Files/Chap01/suresh.py"
john 1
john 2
john 3
Terry 1
Terry 2
Terry 3
Eric 1
Eric 2
Eric 3
For Loop done!
[snandago@sureshn Chap01]$
```
#### For loops - Exercise
```
names = ['john ClEEse','Eric IDLE','michael']
names1 = ['graHam chapman','TERRY','terry jones']
msg = 'You are invited to the party on saturday.'
names.extend(names1)
#names += names + names1
for index in range(2):
names.append(input('Enter a new name: '))
for name in names:
msg1 = f'{name.title()}! {msg}'
print(msg1)
```
```
EssT/Exercise Files/Chap01/suresh.py"
Enter a new name: suresh
Enter a new name: suresh1
John Cleese! You are invited to the party on saturday.
Eric Idle! You are invited to the party on saturday.
Michael! You are invited to the party on saturday.
Graham Chapman! You are invited to the party on saturday.
Terry! You are invited to the party on saturday.
Terry Jones! You are invited to the party on saturday.
Suresh ! You are invited to the party on saturday.
Suresh1! You are invited to the party on saturday.
[snandago@sureshn Chap01]$
```
#### Dictionaries
Name value parsed or key value parsed
```
movie = {
'title' : 'Life of Brian',
'year' : 1979,
'cast' : ['John','Eric','Michael','George','Terry']
}
movie.update({'title' : 'The Holy Grail', 'year': 1975,'cast': ['john']})
print(movie['title'])
print(movie.get('budget','not found')) #we can specify what we get
movie['title'] = ' The Holy grail' #update dictionaries
movie['budget'] = 2500
print(movie.get('budget'))
```
```
[snandago@sureshn Python]$ /usr/bin/python /home/snandago/As/Learnings/Python/suresh
.py
The Holy Grail
not found
2500
[snandago@sureshn Python]$
```
#### Sort() and Sorted()
my_list = [1,5,3,7,2]
my_dict = {'car':4,'dog':2,'add':3,'bee':1}
my_tuple = ('d','c','e','a','b') # immutable
my_string = 'python'
#print(my_list,'original')
#print(my_list.sort())
#print(my_list,'new')
#print(my_list.reverse())
#print(sorted(my_list))
#my_list1 =sorted(my_list)
#print(my_list1)
#sorting tuple
#print(my_tuple,'new')
#print string
#print(my_string,'original')
#print(sorted(my_string))
#print(my_string,)
print(my_dict,'original')
print(sorted(my_dict.items()))
print(my_dict,'new')
#### Exceptions: Try/Except, Raise
Error handling
```
try:
num=int(input('Enter a number between 1 and 30: '))
num1 = 30/num
if num > 30:
raise ValueError(num)
except ZeroDivisionError as err:
print(err, "You can't divide by Zero!!!")
except ValueError as err:
print(err,num, "Bad Value not between 1 and 30!")
except:
print("Invalid Input!")
else:
print("30 divided by",num, "is: ", 30/num)
finally:
print("**Thank you for playing!**")
#try:
#code you want to run
#except:
#executed if error occurs
#else:
#executed if no error
#finally:
#always executed
```
```
[snandago@sureshn Python]$ /usr/bin/python /home/snandago/As/Learnings/Python/suresh.py
[snandago@sureshn Python]$ /usr/bin/python /home/snandago/As/Learnings/Python/suresh[snandago@sureshn Python]$ /usr/bin/python /home/snandago/As/Learnings/Python/suresh
.py
Enter a number between 1 and 30: 0
division by zero You can't divide by Zero!!!
**Thank you for playing!**[snandago@sureshn Python]$ /usr/bin/python /home/snandago/As/Learnings/Python/suresh
.py
Enter a number between 1 and 30: 23
30 divided by 23 is: 1.3043478260869565
**Thank you for playing!**
[snandago@sureshn Python]$ /usr/bin/python /home/snandago/As/Learnings/Python/suresh
.py
Enter a number between 1 and 30: 35
35 35 Bad Value not between 1 and 30!
**Thank you for playing!**
[snandago@sureshn Python]$
```
#### Classes and Objects
```
class Movie:
def __init__(self,title,year,imdb_score,have_seen):
self.title = title
self.year = year
self.imdb_score = imdb_score
self.have_seen = have_seen
def nice_print(self):
print("Title: ", self.title)
print("Year of production: ", self.year)
print("IMDB Score: ", self.imdb_score)
print("I have seen it: ", self.have_seen)
film_1 = Movie("Life of Brian",1979,8.1,True)
film_2 = Movie("The Holy Grail",1975,8.2,True)
#print(film_1.title, film_1.imdb_score)
film_2.nice_print()
Movie.nice_print(film_2)
#Classes are blueprints
#Objects are the actual things you built
#variables => attributes
#functions => methods
```
```
[snandago@sureshn Python]$ /usr/bin/python /home/snandago/As/Learnings/Python/suresh
.py
Title: The Holy Grail
Year of production: 1975
IMDB Score: 8.2
I have seen it: True
Title: The Holy Grail
Year of production: 1975
IMDB Score: 8.2
I have seen it: True
[snandago@sureshn Python]$
```
#### inheritance
Python Inheritance. Inheritance allows us to define a class that inherits all the methods and properties from another class
```
class Person:
def move(self):
print("Moves 4 paces")
def rest(self):
print("Gains 4 health points")
class Doctor(Person):
def heal(self):
print("Heals 10 health points")
character1=Doctor()
character1.heal()
```
```
[snandago@sureshn Python]$ /usr/bin/python /home/snandago/As/Learnings/Python/suresh
.py
Heals 10 health points
[snandago@sureshn Python]$ /usr/bin/python /home/snandago/As/Learnings/Python/suresh
.py
Gains 4 health points
[snandago@sureshn Python]$
```
#### Modules
import modules , program created by other program.
datetime random string os math browser
```
import platform , string, os, system
print(platform.python_version())
```
```
[snandago@sureshn Python]$ /usr/bin/python /home/snandago/As/Learnings/Python/suresh
.py
3.7.6
[snandago@sureshn Python]$
```
#### Zip/Unzip
#### Encrypt & decrypt
```
def enigma_light():
# create keys string
keys = 'abcdefghijklmnopqrstuvwxyz !'
# autogenerate the values string by offsetting original string
values = keys[-1] + keys[0:-1]
#print(keys)
#print(values)
# create two dictionaries
dict_e = dict(zip(keys,values))
dict_d = dict(zip(values,keys))
# OR create 1 and then flip
#dict_e = dict(zip(keys,values))
#dict_d = {value:key for key, value in dict_e.items()}
#user input 'the message' and mode
msg = input('Enter your secret message quietly: ')
mode = input('Crypto mode: encode (e) OR decrypt as default: ')
# run encode or decode
if mode.lower() == 'e':
new_msg = ''.join([dict_e[letter] for letter in msg.lower()])
else:
new_msg = ''.join([dict_d[letter] for letter in msg.lower()])
return new_msg.capitalize()
# return result
# clean and beautify the code
print(enigma_light())
```
```
[snandago@sureshn Python]$ /usr/bin/python /home/snandago/As/Learnings/Python/crypto.py
Enter your secret message quietly: Hello
Crypto mode: encode (e) OR decrypt as default: e
Gdkkn
[snandago@sureshn Python]$ /usr/bin/python /home/snandago/As/Learnings/Python/crypto.py
Enter your secret message quietly: Gdkkn
Crypto mode: encode (e) OR decrypt as default:
Hello
[snandago@sureshn Python]$
```
#### Project
```
#import modules
from random import randrange as r
from time import time as t
# ask how many questions user wants
no_questions = int(input('How many questions do you want?: '))
max_num =int(input('Highest number used in practice?: '))
#set score start at zero
score = 0
answer_list = []
#loop through number of questions
start = t()
for q in range(no_questions):
num1,num2 = r(1,max_num+1),r(1,max_num+1)
ans = num1 * num2
u_ans =int(input(f'{num1} X {num2} = '))
answer_list.append(f'{num1} X {num2} = {ans} you:{u_ans}')
if u_ans == ans:
score += 1
end = t()
print(f'Thank you for playing! \nYou got {score} out of {no_questions} ({round(score/no_questions*100)}%) correct in {round(end-start,1)} seconds ({round((end-start)/no_questions,1)}seconds/question)')
for a in answer_list:
print(a)
# create two random numbers and calc answer
# show user the question
# capture answer and modify user score
# output final score
```
```
[snandago@sureshn Python]$ /usr/bin/python /home/snandago/As/Learnings/Python/crypto.py
How many questions do you want?: 2
Highest number used in practice?: 10
8 X 4 = 32
9 X 10 = 90
Thank you for playing!
You got 2 out of 2 (100%) correct in 21.0 seconds (10.5seconds/question)
8 X 4 = 32 you:32
9 X 10 = 90 you:90
[snandago@sureshn Python]$
```