Copy these codes below and run it on your ios / android 👌🏻
# Basic code:
print("aviral paudel")
print('o----')
output: aviral paudel
o----
|||||
Program to print **********
print('*' * 10)
output: **********
Program to print the price of an object
price = 10
price = 20
print(price)
output: 20
4 We check in a patient named Aviral Paudel. He is 19 years old and is a new patient.
solution,
Full_name = 'Aviral Paudel'
age = 19
is_new = True
# Getting Input
Program to get the input name
name = input('What is your name ?')
print('Hi' + name)
output: What is your name ?
Hi name
2>> Ask two questions: person's name and favourite color. Then print a message like "Aviral likes blue "
soln,
name = input ("What is your name?")
favourite_color = input("What is your favourite color?")
print(name +'likes'+ favourite color)
output: name likes color
#Type Conversion
Program to get the type and age of the person
birth_year = input('Birth Year : ')
print(type(birth_year))
age = 2020 - int(birth_year)
print(type(age))
print(age)
output: Birth year: 2020
<class 'str'>
< class 'int'>
37
2>> Ask a user their weight (in pounds), convert it to kilograms and print on the terminal.
soln,
weight_lbs = input('weight(lbs):')
weight_kg = int(weight_lbs) * 0.45
print(weight kg)
output : weight(lbs) : 160
72.0
#Strings
1>> Single quote string : Examples ↓↓↓
course = 'Python for Beginners'
print(course)
output: Python for Beginners
course = ' Python for "Beginners" '
print (course)
output: Python for "Beginners"
2>> Double quote string: Example ↓↓↓
course = "Python's Course for Beginners"
print(course)
output: Python's Course for Beginners
3>> Triple quote string : Example ↓↓↓
course = '''
Hi Aviral what's up?
Where are you from?
what is your age?
'''
print(course)
output: Hi Aviral what's up?
Where are you from?
What is your age?
# String and index combination
Positive index : Example ↓
course = 'Python for Beginners'
print(course[0])
Output : P
Negative index : Example ↓
course = 'Python For Beginners'
print(course[-1])
Output : S
course = 'Python For Beginners'
print(course[0:])
Output : Python For Beginners
course = 'Python For Beginners'
print(course[:])
Output : Python For Beginners
course = 'Python For Beginners'
another = course[:]
print(another)
Output : Python For Beginners
name = 'Aviral'
print(name[1:-1])
Output : vira
#Formatted Strings
first = 'Aviral'
last = 'Paudel'
message = first + '['+ last + '] is a coder'
print(message)
Output : Aviral[Paudel] is a coder
first = 'Aviral'
last = 'Paudel'
msg = f'{first} [{last}] is a coder'
print(msg)
Output : Aviral [Paudel] is a coder
#String Methods
course = 'Python for Beginners'
print(len(course))
Output : 20
course = 'Python for Beginners'
print(course.upper())
Output : PYTHON FOR BEGINNERS
course = 'Python for Beginners'
print(course.find('P')
Output : 0
course = 'Python for Beginners'
print(course.find('Beginners'))
Output : 11
course = 'Python for Beginners'
print(course.replace('Beginners','Absolute Beginners'))
Output : Python for Absolute Beginners
course = 'Python for Beginners'
print(course.replace('P','J'))
Output : Jython for Beginners
course = 'Python for Beginners'
print('Python' in course)
Output : True
course = 'python for beginners'
print(course.title())
Output : Python For Beginners
#Arithmetic Operations
Addition Operators
print(10 + 3)
Output : 13
Subtraction Operator
print(10 - 3)
Output : 7
Multiplication Operator
print(10 * 3)
Output : 30
Division Operator
print(10 / 3)
Output : 3.3333333333333335
print(10 // 3)
Output : 3
Modulo Operator
Output : 1
Exponent Operator
print(8 ** 3)
Output : 512
Augmented assignment Operator
Output : 13
Operator Precedence
x = (2 + 3) * 10 - 3
print(x)
Output : 47
#Math functions
Round function
Output : 3
Absolute(abs) function
print(abs(-2.9))
Output : 2.9
Math Ceil
import math
print(math.ceil(2.9))
Output : 3
Math Floor
import math
print(math.floor(2.9))
Output : 2
# if statements
is_hot = True
if is_hot:
print("It's a hot day")
print("Enjoy your day")
Output : It's a hot day
Enjoy your day
is_hot = False
if is_hot:
print("It's a hot day")
print("Enjoy your day")
Output : Enjoy your day
is_hot = True
if is_hot:
print("It's a hot day")
print("Drink plenty of water")
else:
print("It's a cold day")
print("wear warm clothes")
print("Enjoy your day")
Output : It's a hot day
Drink plenty of water
Enjoy your day
is_hot = False
if is_hot:
print("It's a hot day")
print("Drink plenty of water")
else:
print("It's a cold day")
print("Wear warm clothes")
print("Enjoy your day")
Output : It's a cold day
Wear warm clothes
Enjoy your day
is_hot = False
is_cold = True
if is_hot:
print("It's a hot day")
print("Drink plenty of water")
elif is_cold:
print("It's a cold day")
print("wear warm clothes")
else:
print("It's a lovely day")
print("Enjoy your day")
Output : It's a cold day
Wear warm clothes
Enjoy your day
is_hot = False
is_cold = False
if is_hot:
print("It's a hot day")
print("Drink plenty of water")
elif is_cold:
print("It's a cold day")
print("wear warm clothes")
else:
print("It's a lovely day")
print("Enjoy your day")
Output : It's a lovely day
Enjoy your day
The price of a house is 1M$ . If a buyer has good credit, they need to put down 10% otherwise , they need to put down 20% , write a program with these above rules and display / print the down payment required for a buyer with a good credit .
Solution ;
price = 1000000
has_good_credit = True
if has_good_credit :
down_payment = 0.1 * price
else:
down_payment = 0.2 * price
print ( f"Down payment: ${down_payment} ")
Output : Down payment: $100000.0
#Logical Operators
If a applicant has high income and good credit then the applicant is Eligible for loan. Write a program on it .
Solution;
has_high_income = True
has_good_credit = True
if has_high_income and has_good_credit :
print("Eligible for loan")
Output : Eligible for Loan
If a applicant has high income or good credit then the applicant is Eligible for loan. Write a program on it .
Solution;
has_high_income = False
has_good_credit = True
if has_high_income or has_good_credit :
print("Eligible for loan")
Output : Eligible for Loan
Write a program if applicant has good credit and doesn't have criminal record .
Solution;
has_good_credit = True
has_criminal_record = False
if has_good_credit and not has_criminal_record:
print("Eligible for loan")
Output : Eligible for Loan
#Comparison Operators
Types of Comparison operators :
i] < ( less than )
ii] > ( greater than )
iii] < = ( less than or equal to )
iv] > = ( greater than or equal to )
v] = = ( equality operator)
Write a program if temperature is greater than 30 print it's a hot day otherwise if it's less than 10 it's a cold day otherwise it's neither hot nor cold .
Solution;
temperature = int (input ("Enter the temperature = "))
if temperature > 30 :
print(" it's a hot day ")
elif temperature < 10 :
print (" it's a cold day ")
else:
print ( " neither hot nor cold ")
Write a program if name is less than 3 characters long print name must be at least 3 characters otherwise if it's more than 50 characters long print name can be a minimum of 50 characters otherwise print name looks good.
Solution;
name = " Aviral Paudel "
if len(name) < 3:
print("Name must be at least 3 chracters.")
elif len(name) > 50:
print("Name must be a maximum of 50 chracters.")
else:
print("Name looks good")
#Weight converter
weight = int(input("Weight: "))
unit = input('(L)bs or (K)g:')
if unit.upper() == "L":
converted = weight * 0.45
print( f"you are{converted}kilo ")
else:
converted = weight / 0.45
print( f"you are{converted}pound ")
#While loops
i = 1
while i <= 5 :
print(i)
i = i + 1
print("Done")
Output : 1
2
3
4
5
Done
i = 1
while i <= 5 :
print('*' * i)
i = i + 1
print("Done")
Output : *
**
***
****
*****
#Guess Game
secret_number = 9
guess_count = 0
guess_limit = 3
while guess_count < guess_limit:
guess = int(input('Guess :'))
guess_count += 1
if guess == secret_number:
print("You won!")
break
else:
print("Sorry you failed")
#Car Game
command = " "
started = False
while True:
command = input(">").lower()
if command == "start":
if started:
print("car is already started!")
else:
started = True
print("car started ...")
elif command == "stop":
if not started:
print("car is already stopped!")
else:
started = False
print("car stopped.")
elif command == "help":
print("""
start - to start the car
stop - to stop the car
quit - to quit
""")
elif command == "quit":
break
else:
print("Sorry, I don't understand that")
#For Loops
for item in 'Python ' :
print(item)
Output : P
y
t
h
o
n
for item in ['Aviral' , 'Everest', 'MarvelCode']:
print(item)
Output : Aviral
Everest
MarvelCode
for item in [ 1,2,3,4,5 ]:
print(item)
Output : 1
2
3
4
5
for item in range(5):
print(item)
Output : 0
1
2
3
4
for item in range(5, 10):
print(item)
Output : 5
6
7
8
9
for item in range (5,10,2):
print(item)
Output : 5
7
9
WAP to calculate the total cost of all the items in a shopping cart.
prices = [10 , 20 , 30 ]
total = 0
for price in prices :
total += price
print( f"Total:{total}")
Output : 60
#Nested Loops
for x in range (3):
for y in range (2):
print( f'({x} , {y})')
Output : (0 , 0)
(0 , 1)
(1 , 0)
(1 , 1)
(2 , 0)
(2 , 1)
numbers = [5, 2, 5, 2, 2]
for x_count in numbers:
output = ' '
for count in range (x_count):
output += 'x'
print(output)
Output : xxxxx
xx
xxxxx
xx
xx
#Lists
Ytt : 1:56:26
names = ['Aviral' , 'Marvel' , 'Ironman']
print(names)
Output : ['Aviral', 'Marvel', 'Ironman']
Ytt : 1:56:55
names = ['Aviral' , 'Marvel' , 'Ironman']
print(names[0])
Output : Aviral
Ytt : 1:56:59
names = ['Aviral' , 'Bob' , 'Mosh', 'Sarah', 'Mary']
print(names[2])
Output : Mosh
Ytt : 1:57:06
names = ['Aviral' , 'Bob' , 'Mosh', 'Sarah', 'Mary']
print(names[-1])
Output : Mary
names = ['Aviral' , 'Bob' , 'Mosh', 'Sarah', 'Mary']
print(names[2:])
Output : ['Mosh', 'Sarah', 'Mary']
names = ['Aviral' , 'Bob' , 'Mosh', 'Sarah', 'Mary']
names[0] = 'Everest'
print(names)
Output : ['Everest', 'Bob', 'Mosh', 'Sarah', 'Mary']
WAP to find the largest number in a list .
numbers = [3,6,2,8,4,10]
max = numbers[0]
for number in numbers:
if number > max:
max = number
print(max)
Output : 10
or,
numbers = [3,6,2,10,8,4]
max = numbers[0]
for number in numbers:
if number > max:
max = number
print(max)
Output : 10
#2DLists
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
print(matrix[0][1])
Output : 2
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
matrix[0][1] = 20
print(matrix[0][1])
Output : 20
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
for row in matrix:
for item in row:
print(item)
Output : 1
2
3
4
5
6
7
8
9
# Lists Methods
numbers = [5, 2, 1, 7, 4]
numbers.append(20)
print(numbers)
Output : [5, 2, 1, 7, 4, 20]
numbers = [5, 2, 1, 7, 4]
numbers.insert(0, 10)
print(numbers)
Output : [10, 5, 2, 1, 7, 4]
numbers = [5, 2, 1, 7, 4]
numbers.remove(5)
print(numbers)
Output : [2, 1, 7, 4]
numbers = [5, 2, 1, 7, 4]
numbers.clear()
print(numbers)
Output : [ ]
numbers = [5, 2, 1, 7, 4]
numbers.pop()
print(numbers)
Output : [5, 2, 1, 7]
numbers = [5, 2, 1, 7, 4]
print(numbers.index(5))
Output : 0
numbers = [5, 2, 1, 7, 4]
print(50 in numbers)
Output : False
numbers = [5, 2, 1, 5, 7, 4]
print(numbers.count(5))
Output : 2
numbers = [5, 2, 1, 5, 7, 4]
print(numbers.sort())
Output : None
numbers = [5, 2, 1, 5, 7, 4]
numbers.sort()
numbers.reverse()
print(numbers)
Output : [7, 5, 5, 4, 2, 1]
numbers = [5, 2, 1, 5, 7, 4]
numbers2 = numbers.copy()
numbers.append(10)
print(numbers2)
Output : [5, 2, 1, 5, 7, 4]
WAP to remove the duplicates in a list .
solution,
numbers = [2, 2, 4, 6, 3, 4, 6, 1]
uniques = []
for number in numbers :
if number not in uniques:
uniques.append(number)
print(uniques)
Output : [2, 4, 6, 3, 1]
#Tuples
coordinates = [1,2,3]
x, y, z = coordinates
print(y)
Output : 2
#Dictionaries
customer = {
"name": "John Smith",
"age" : 30,
"is_verified": True
}
print(customer["name"])
Output : John Smith
customer = {
"name": "John Smith",
"age" : 30,
"is_verified": True
}
print(customer["age"])
Output : 30
customer = {
"name": "John Smith",
"age" : 30,
"is_verified": True
}
print(customer["birthday"])
KeyError
'birthday'
customer = {
"name": "John Smith",
"age" : 30,
"is_verified": True
}
print(customer.get("birthday"))
Output : None
customer = {
"name": "Aviral KC",
"age" : 20,
"is_verified": True
}
print(customer.get("birthday", "jan 1 2000"))
Output : jan 1 2000
customer = {
"name": "Aviral KC",
"age" : 20,
"is_verified": True
}
customer["name"] = "Aviral KC"
print(customer["name"])
Output : Aviral KC
customer = {
"name": "Aviral KC",
"age" : 20,
"is_verified": True
}
customer["birthdate"] = "Jan 1 2000"
print(customer["birthdate"])
Output : jan 1 2000
phone = input("Phone: ")
digits_mapping = {
"1": "One",
"2": "Two",
"3": "Three",
"4":"Four"
}
output = ""
for ch in phone:
output += digits_mapping.get(ch, "!") + " "
print(output)
Output : One Three Four !
#Functions
def greet_user():
print('Hi there!')
print('welcome aboard')
print("Start")
greet_user()
print("Finish")
Output : Start
Hi there!
welcome aboard
Finish
#Parameters
def greet_user(name):
print(f'Hi {name}!')
print('welcome aboard')
print("Start")
greet_user("Aviral")
print("Finish")
Output : Start
Hi Aviral!
welcome aboard
Finish
def greet_user(name):
print(f'Hi {name}!')
print('welcome aboard')
print("Start")
greet_user("Aviral")
greet_user("Maya")
print("Finish")
Output : Start
Hi Aviral!
welcome aboard
Hi Maya!
welcome aboard
Finish
def greet_user(first_name, last_name):
print(f'Hi {first_name} {last_name}!')
print('welcome aboard')
print("Start")
greet_user("Aviral","Kc")
greet_user("Maya", "Smith")
print("Finish")
Output : Start
Hi Aviral Kc!
welcome aboard
Hi Maya Smith!
welcome aboard
Finish
#Keyword Arguments
def greet_user(first_name, last_name):
print(f'Hi {first_name} {last_name}!')
print('welcome aboard')
print("Start")
greet_user("Aviral","Maya")
print("Finish")
Output : Start
Hi Aviral Maya!
Welcome aboard
Finish
def greet_user(first_name, last_name):
print(f'Hi {first_name} {last_name}!')
print('Welcome aboard')
print("Start")
greet_user(last_name="Aviral", first_name="Barsha")
print("Finish")
Output : Start
Hi Barsha Aviral !
Welcome aboard
Finish
def calc_cost(total, shipping, discount):
print(f'Amounts = {total}, {shipping}, {discount}')
print("Start")
calc_cost(total=50, shipping=5, discount=0.1)
print("Finish")
Output : Start
Amounts = 50, 5, 0.1
Finish
def square(number):
return number * number
result = square(3)
print(result)
Output : 9
def square(number):
print(number * number)
print (square(4))
Output : 16
#Exceptions
try:
age = int(input('Age:'))
print(age)
except ValueError:
print('Invalid value')
Output : Age : 20
20
try:
age = int(input('Age:'))
print(age)
except ValueError:
print('Invalid value')
Output : Age : abc
Invalid value
try:
age = int(input('Age:'))
income = 2000
risk = income / age
print(age)
except ZeroDivisionError:
print('Age cannot be 0 .')
except ValueError:
print('Invalid value')
Output : Age : 0
Age cannot be 0 .
try:
age = int(input('Age:'))
income = 2000
risk = income / age
print(risk)
except ZeroDivisionError:
print('Age cannot be 0 .')
except ValueError:
print('Invalid value')
Output : Age : 20
100.0
#Comments
# this is my first python program
print ('Hello World !') # printing Hello World !
Output : Hello World !
#program to print love using python
from turtle import *
bgcolor("black"); color("green","yellow") # here we give color to our shape
width(4);left(122);forward(120)
begin_fill()
circle(-32,185);left(125)
circle(-37,185); home()
end_fill()
ht(); done()
Output :
#Classes
class Point:
def move (self):
print("move")
def draw(self):
print("draw")
point1 = Point()
point1.draw()
Output : draw
class Point:
def move (self):
print("move")
def draw(self):
print("draw")
point1 = Point()
point1.x = 10
point1.y = 20
print(point1.x)
point1.draw()
Output : 10
draw
class Point:
def move (self):
print("move")
def draw(self):
print("draw")
point1 = Point()
point1.x = 10
point1.y = 20
print(point1.x)
point1.draw()
point2 = Point()
point2.x = 1
print(point2.x)
Output : 10
draw
1
#Constructors
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def move (self):
print("move")
def draw(self):
print("draw")
point = Point(10, 20)
print(point.x)
Output : 10
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def move (self):
print("move")
def draw(self):
print("draw")
point = Point(10, 20)
point.x = 11
print(point.x)
Output : 11
class Person:
def talk(self):
print("talk")
john = Person()
john.talk()
Output : talk
class Person:
def __init__(self, name):
self.name = name
def talk(self):
print("talk")
aviral = Person("Aviral Skt")
print(aviral.name)
aviral.talk()
Output : Aviral Skt
talk
class Person:
def __init__(self, name):
self.name = name
def talk(self):
print(f"Hi, I am {self.name}")
aviral = Person("Aviral Skt")
aviral.talk()
Output : Hi, I am Aviral Skt
class Person:
def __init__(self, name):
self.name = name
def talk(self):
print(f"Hi, I am {self.name}")
aviral = Person("Aviral Skt")
aviral.talk()
maya = Person("Maya Ktm")
maya.talk()
Output : Hi, I am Aviral Skt
Hi, I am Maya Ktm
#inheritance
class Mammal:
def walk(self):
print("walk")
class Dog(Mammal):
pass
class Cat(Mammal):
pass
dog1 = Dog()
dog1.walk()
Output : walk
class Mammal:
def walk(self):
print("walk")
class Dog(Mammal):
def bark(self):
print("bark")
class Cat(Mammal):
def be_annoying(self):
print("annoying")
cat1 = Cat()
cat1.walk()
Output : walk
#Rolling the Dice
import random
import time
min = 1
max = 6
roll_again = "yes"
while True:
if roll_again == "yes" or roll_again == "y":
print("Rolling the dice ...")
time.sleep(1)
print('')
print('*' * 10)
print('The values are ...')
time.sleep(2)
print('')
print(random.randint(min,max))
print(random.randint(min,max))
time.sleep(1)
print('')
print('*' * 10)
roll_again = input('Roll the dice again? yes/no :')
elif roll_again == "no" or roll_again == "n":
print('Thank you for rolling the dice at least')
break
else:
print('try again later')
break
0 Comments