Python Codes from pc


Image source:Negative Space



name=input("Enter name:")

color=input("Enter fav color:")

print(name,"likes",color)


____________________________________________________________________________



weight=int(input("Enter weight:"))

option=input("\nIn pound or kg?\np:Pound\nk:kilogram\nEnter option:")

if(option.lower()=="p"):

    weight_in_kg=0.4535*weight

    print("Your weight_in_kg:",weight_in_kg)

elif(option.lower()=="k"):

    weight_in_pound=2.2046*weight

    print("Your weight_in_pound:",weight_in_pound)


____________________________________________________________________________


print("Price of house : 1 million dollar")

good_credit=False 


if good_credit:

    discount=10000000*0.1

    price=10000000-discount

    print("Discounted price:",price)


else:

    discount=10000000*0.2

    price=10000000-discount

    print(price)


____________________________________________________________________________



name=input("Enter name:")

if len(name)<3:

    print("Name must be atleast 3 characters")

elif len(name)>50:

   print("Name can be max 50")

else:

   print("Name looks good")


____________________________________________________________________________

print("Type help for instruction\n")

input1=""

started = False

stopped= False

while True:

    input1=input(">").lower()

    if input1=="help":

        print("\nstart->To start the car\nstop->To stop the car\nQuit->to exit")


    elif input1=="start":

        if started:

            print("Car is already started")

        else:

            started=True

            print("Car started.........>>>>>>>>>>Ready to go")

    elif input1=="stop":

        if stopped:

            print("Car is already stationary")

        else:

            stopped=True

            print("Car stopped ....||||||")

    elif input1=="quit":

        break

    else:

        print("Sorry i cannot understand")





______________________________________________________________________________

numbers=[2,2,2,2,5]

for x_count in numbers:

    output= ' '

    for count in range(x_count):

        output+= 'x'

    print(output)

    

#______________________________________________________________________


list=[]

number_of_terms=int(input("Enter no. of terms:"))

for i in range(0,number_of_terms):

    input1=int(input("Enter list of no to find largest no:"))

    list.append(input1)


max=list[0]                 

for next_no in list:

    if next_no>max:

        max=next_no

print(max)

        

    



Practice 3

***************LIST*********************************************************
list=[1,3,4,2,5]
friends=["hi ","sam ","dam ","hello"]
friends.insert(2,"bomerjack")
list.append(6)
list.extend(friends)
list.insert(2,10)
friends.sort()
friends.reverse()
print(friends)
print(list)

***************TUPLE*******************************************************************
used when you don't need to change it later (i.e immutable,whereas list is mutable)

***************FUNCTION*******************************************************************
def greet(name,std):
    print("Hi",name,"you are from ",std)

name=input("Enter name:")
std=input("Enter your qualification:")
greet(name,std)
Return in function returns the value of the function

#**************IF AND ELSE******************************************************************
PROGRAM1:
def max_num(num1,num2,num3):
    if(num1>=num2 and num1>=num3):
        print(num1,"is greater")
    elif(num2>=num1 and num2>=num3):
        print(num2,"is greater")
    else:
        print(num3,"is greater")

num1=int(input("Enter num1:"))
num2=int(input("Enter num2:"))
num3=int(input("Enter num3:"))
max_num(num1,num2,num3)

##PROGRAM 2(CALCULATOR):
num1=int(input("Enter num1:"))
op=input("Enter operator:")
num2=int(input("Enter num2:"))

if(op=="+"):
    print (num1+num2)
elif(op=="-"):
    print (num1-num2)
elif(op=="/"):
    print (num1/num2)
elif(op=="*"):
    print (num1*num2)
elif(op=="%"):
    print (num1%num2)
else:
    print("Invalid operator!")

**************DICTIONARY********************************************************
monthconversions={
    "Jan":"January",
    "Feb":"February",
    "Mar":"March",
    "Apr":"April"
    }
print(monthconversions.get("Jan"))
OUTPUT:January
IF THE DESIRED INPUT IS NOT PRESENT IN THE DICTIONARY OUTPUT IS NONE



**************WHILE LOOP********************************************************
 
secret_word="giraffe"
guess=""
guess_count=0
out_of_guesses = False
while guess !=secret_word and not (out_of_guesses):
    if guess_count<3:
        guess=input("Enter your guess:")
        guess_count=guess_count+1
    else:
        out_of_guesses = True

if out_of_guesses:
    print("Your guesses have ended,Refresh to play again!")
else:
    print("You win")

**************FOR  LOOP******************************************************************
EVEN NO. ADDITION USING FOR LOOP
list=[1,2,3,4,5,6,7,8]
addition=0
for number in list:
    if(number%2==0):
        addition=addition+number
print("Even no. addition:",addition)

##ODD ADDITION USING FOR LOOP BUT WITH RANGE()
addition=0
for number in range(1,9):       ##In range(a,b) the b is not taken into consideration
         if(number%2!=0):
            addition=addition+number
print("Odd no. addition:",addition)

EXPONENT FUNCTION BUT USING FOR LOOP

def exp(base,power):
    result=1
    for number in range(power):     #the "number" here goes to each individual item in the range or list etc
        result=result*base              #1)base 2)base*base 3)base*base*base
    return result                           #will not return(value) until it is multipled in the range of power given by the user
base=int(input("Enter base:"))
power=int(input("Enter power:"))
print(exp(base,power))


************Translator************************************************************************
def translate(phrase):
    translation=""
    for letter in phrase:
        if letter.lower() in "aeiou":
            if letter.isupper():
                translation=translation+"G"     #if capital vowel is found then capital G
            else:
                translation=translation+"g"         #if small vowel then small g
        else:
            translation=translation+letter          #if the letter is not vowel then return the word as it is
    return translation

phrase=input("Enter the phrase:")
print(translate(phrase))

Vowel counter

word1=input("Enter the word:")
word=word1.lower()
list=['a','e','i','o','u']
count=0
#def counter(word):
for letter in word:                                    #for the letter in word given by user
    if letter in list:                                      #if that letter is present in the list above
        count+=1                                          #increase the count
print("Count of vowel:",count)


#**********TRY-EXCEPTION************************************************************ 
try:
    #ans=10/0
    input=int(input("Enter no."))
    print(number)
except ZeroDivisionError as err:
              print(err)
except ValueError as err:
              print(err)

**********READING FILES**********************************************************************
employee_file=open("employee.txt","r")
print(employee_file.read())                   #1)
for lines in employee_file.readlines():         #2)
    print(lines)
print(employee_file.readline())               #3)
print(employee_file.readlines())              #4)
employee_file.close()

**********WRITING FILES**********************************************************************
employee_file=open("employee.txt","a")      #a here appends to the file,if we use w then whatever we write in the folowing line will be replaced
employee_file.write("\n Bishal 41")
employee_file.close()


**********MODULES AND PIP************************************************************
we can install inbuilt modules of python ,the info is available online in their site.




            
        

*****************************************************        

list=[]                                                                                                  #creating list 
no_of_terms=int(input("Enter no. of terms:"))                                     #asking the no. of term
for number in range(0,no_of_terms):                                                  #running for loop for range 0 to no of term
    inputs=int(input("Enter the numbers:"))                                          #getting inputs
    list.append(inputs)                                                                          #appending those inputs
    
max=list[0]                                                                                   #considering the first element in the lis to be max
for next_no in list:                                                                       #each no is checked one by one in the list
    if next_no>max:                                                                        #if the no is greater than first no change the max,continue doing until you find the greatest
        max=next_no                                                                      #after checking all the nos and confirming the max ,come out of the loop
print("Max no. is",max)                                                               #print the mas




















Practice 5

#************************ANAGRAM************************************************
str1=input("Enter string1:")
str2=input("Enter string2:")
sorted_str1=sorted(str1)
sorted_str2=sorted(str2)

if len(sorted_str1)==len(sorted_str2):
    if sorted_str1==sorted_str2:
        print("Both the strings are anagram")
    else:
         print("The strings are not anagram")
else:
    print("The strings are not anagram('Because the no. of character is not same')")


******************SUM OF DIGITS OF THE GIVEN NO******************************************
result=0
number=int(input("Enter the no. to find sum:"))
while number>0:
    digit=number%10
    result=result+digit
    number=number//10
print("The sum:",result)

************************UNIQUE NUMBERS IN THE LIST************************************************

n=int(input("Enter number of inputs:"))
list1=[]
for number_of_times in range(n):
    inputs=int(input("Enter  inputs:"))
    list1.append(inputs)
    
unique_list=[]
for each_number in list1:
    if each_number not in unique_list:              #if no. in the list is not present in uniquelist then add it to uniquelist
        unique_list.append(each_number)
print(unique_list)


************************FACTORIAL ************************
def factorial(num):
    if num==1:
        return 1
    else:
        return num*factorial(num-1)

num=int(input("Enter num to find factorial:"))
fact=factorial(num)
print("Factorial:",fact)

************************MERGE SORT************************

def mergesort(main_list):
    if len(main_list)>1:
        mid=len(main_list)//2
        left_list = main_list[:mid]
        right_list = main_list[mid:]
        mergesort(left_list)
        mergesort(right_list)
        i=0
        j=0
        k=0
        while i<len(left_list) and j<len(right_list):               #i starts from beginning of the left list and travveerses until it becomes greater than the length of the list that we have 
            if left_list[i]<right_list[j]:                                 #element in the left list is smaller than that element wil come
                main_list[k] = left_list[i]
                i=i+1
                k=k+1
            else:
                main_list[k] = right_list[j]
                j=j+1
                k=k+1
        while i<len(left_list):                                             #if the element is left out then insert it directly into the main_list similarly for the right list below
            main_list[k] = left_list[i]
            i=i+1
            k=k+1
        while i<len(right_list):
             main_list[k] = right_list[j]
             j=j+1
             k=k+1

number=int(input("Enter number of inputs:"))
main_list=[]
for number_of_times in range(number):
     inputs=int(input("Enter  inputs:"))
     main_list.append(inputs)

mergesort(main_list)
print("Sorted list:",main_list)


***********************


*********adding default value in argument or function calling*********************************
def print_info(name="Someone" , age="unknown"):
    print("the name is",name,"the age is ",age)
print_info("sam")



**********************accepting an array in a argument i.e infinite argument********************

def print_people(*people):      #this * indicates we gonna accept infinite argument
    i=0
    for each_person in people:
        i=i+1
        print("The number  ",i,"person name is ",each_person)

print_people("Sam","Zeon","Kevin","Charles")


************************while +if loop eg************************************************************
run=True
count=1
while run==True:
    if count==100:
        run=False
    else:
        print(count)
        count=count+1

****************************MAGIC CALCULATOR**********************************************
import re
print("Calculator")
print("Enter quit to stop")
run=True
previous_value=0
def calculator():
    global run
    global previous_value
    if previous_value==0:
        equation=input("Enter the equation:")
    else:
        equation=input(str(previous_value))
    
    if equation=="quit":
        run=False
    else:
        equation=re.sub('[a-zA-Z,.:()" "]',' ' ,equation)
        if previous_value==0:
            previous_value=eval(equation)
        else:
            previous_value=eval(str(previous_value)+equation)
        
        
while run==True:
    calculator()


******************************RANDOMRANGE AND BREAK IN  WHILE **************
import random

playerhp=300
enemyl=70
enemyh=80

while playerhp>0:
    dmg=random.randrange(enemyl,enemyh)
    playerhp=playerhp-dmg
    if playerhp<=30:
        playerhp=30
    print ("Your enemy have attacked with",dmg,"damage and your current hp:",playerhp)

    if playerhp==30:
        print("You have been teleported to nearest hospital and you gain extra 100 hp")
        playerhp=playerhp+100
        print("Your current hp :",playerhp)
        break
    
list1=[5,4,3,2,1]
for i in list1:
    print(i)












    


    
        
    
    
    




       
    
        
            
            
            
            
        
        
    
    
    
    
    


    
    





        
        
  

    
    






Comments

Popular posts from this blog

Pattern python