Search This Blog

Practice questions for Python

ques: 1] Read a number & check whether it is pos. or negative? 

Solution:

try:

    num= int(input("Enter a number:"))

    if(num>0):

        print("number is positive")

    else:

        print("number is negative")


except:

    print("Please enter a number only. Thank You!")


Output: Enter a number:-1

number is negative


ques: 2] Read a number check whether it is odd or even?

Solution:

try:

    num= int(input("Enter a number:"))

    if(num%2==0):

        print("number is even")

    else:

        print("number is odd")


except:

    print("Please enter a number only. Thank You!")

Output:

python odd_even.py

Enter a number:100

number is even

ques: 3] Read the age of a person & display whether that person can vote or can not vote.

Solution:

try:

    Age= int(input("Enter your age:"))

    if(Age>=18):

        print("You're eligible to vote in elections!")

    elif(Age<=0):

        print("Please enter the correct age. Thank You!")

    else:

        print("You are under 18. You cannot Vote. Better Luck next time!")


except:

    print("Please enter a number only. Thank You!")

Output:

python castavote.py

Enter your age:-25

Please enter the coorect age. Thank You!

Ques 4] Read two numbers & display largest number

Solution:

try:

    num1,num2 = map(int, input().split())

    #map allocates the numbers at the correct position. Note that we don’t have to explicitly specify split(‘ ‘)

    # because split() uses any whitespace characters as a delimiter as default.

    if (num1<num2):

        print(num2,'is the largest')

    else:

        print(num1,'is the largest')

except:

    print("Please enter the correct values!")


Output: python largestnum.py
3 5555
5555 is the largest

Learning Python : Day 03

 











Phase 1:


#Step 1

word_list = ["aardvark", "baboon", "camel"]

chosen_word=random.choice(word_list)
print(chosen_word)

guess=input("Guess the Letter:").lower()

j=0
for i in chosen_word:
if i == guess:
j+=1
print(f'right: {j}')
else:
print('wrong')


Phase 2: Replace the underscores/blanks with the matched letter

display=[]

for i in chosen_word:
display+='_'
guess = input("Guess a letter: ").lower()
j=0
for letter in chosen_word:
if letter == guess:
display[j]=letter
j+=1
else:
j+=1
print(display)

Second Solution:

word_length=len(chosen_word)
display=[]
for _ in range(word_length):
display+="_"

for pos in range(word_length):
letter=chosen_word[pos]
if letter==guess:
display[pos]=letter

print(display)


Output:


Pssst, the solution is aardvark.
Guess a letter: a
['a', 'a', '_', '_', '_', 'a', '_', '_']

Phase 3: Guess until all the _ of the display are replaced by the chosen word and end the game

end_of_game=False
while(end_of_game!=True):
guess = input("Guess a letter: ").lower()

#Check guessed letter
for position in range(word_length):
letter = chosen_word[position]
if letter == guess:
display[position] = letter
print(display)
if '_' not in display:
end_of_game=True
print('You win')

Output:

Pssst, the solution is baboon.
Guess a letter: b
['b', '_', 'b', '_', '_', '_']
Guess a letter: a
['b', 'a', 'b', '_', '_', '_']
Guess a letter: b
['b', 'a', 'b', '_', '_', '_']
Guess a letter: o
['b', 'a', 'b', 'o', 'o', '_']
Guess a letter: n
['b', 'a', 'b', 'o', 'o', 'n']
You win

Day 04: Python Learning with Angela Yu

 Hey! Here, am on Day 02 of Angela's course. Though my heading says Day 04 which is actually done to stay in order of all the python learning blog posts to date.

Starting WILT blog with checked Day 02 completion in the daily tracker poster. This kinda gives

self-satisfaction.

So, the end project of today's day was to build a tip calculator. It splits the bill among "n" people on the basis of percentage tip. After all the calculations, it was showing the final amount to pay by "n" people.

Before coming to this project completed 3 exercises: BMI calculator, Your Life in Weeks, and adding a string as 2 digits number. Here, is the end result of the percentage tip calculator project:


Now, comes the What I learned in  DAY:02

1. len() function is incompetent in working with integers. If we even     try; the python compiler will throw an error: print(len(123456)) #It throws the traceback error: Traceback (most recent call last): File "main.py", line 1, in <module> print(len(123456)) TypeError: object of type 'int' has no len() Because we are trying to know the int's (integer) length & len function isn't trained to do so. It can only do the assigned task for strings only. 2. We have data types in python that allows using a different type of entries. a. String Syntax: a="1234" Subscript: The method of pulling out the particular character in the string type data is called a                    subscript. Syntax: print("helloworld"[0]) -> This will print out the H since H is the very first element placed at index 0. Note: 1. print("helloworld"[-1]) -> prints the last character. Initial index starts from zero                                             & last index starts from -1 2. print("123""345") -> concatenates the two strings b. Integer Syntax: a=1234 Note: 1. All the no.s whether positive or negative or whole no. comes under integer data types. 2. print(1234+1234) -> It will give the sum of two numbers. 3. print(123_456_758) -> Computer visulaises it as large no. & prints it after removing underscore:                                           123456758 c. Float Decimal numbers are floating-point numbers. Syntax: a=12.34 d. Boolean -Most Used- Syntax: a= True                 or                a=False Note: 1. While assignments, booleans don't have quotation marks around them.
    Otherwise, it would turn them into a String. 
❌ a="TRUE" ❌ a=true 3. Type checking in python is done by the keyword type(). It basically shows the data type/class type. Syntax: type(12) output: class<int> Example: print(type(len(input("What is your name\n")))) output: What is your namekawal <class 'int'> because we have printed out the length of the string 4. Type Conversion is actually a change. Using this we can implicitly or explicitly change the data type. Syntax: str(a) int(a) float(a) Example: a=100 print(a) print(type(a)) #type of the variable is integer s=str(a) #type casted the int vaiable to string print(s) print(type(s)) 5. Total we have 6 Mathematical Operators in Python which follow the PEMDAS order. The      calculation proceeds from left to right to have the final result. 1. + ( Addition ) 2. - ( Subtraction ) 3. ** ( Exponentiation ) 4. // ( Floor division ) : It chops off the result & gives an int as a final answer. 5. * ( Multiplication ) 6. / ( Division ) : It always gives the float as a final result. PEMDAS is: Paranthesis <- Exponentiation <- Multiplication <- Division <- Addition <- Subtraction     1                        2                            3                        4                    5                6
Example:
(3*3+3/3-3)
First: 3*3: 9
Second: 3/3: 1 9+1-3
Third: 9+1:10
Fourth: 10-3: 7 is the answer.

6.
Number manipulation in python is when we forcibly(using an inbuilt function) changes the               output's behavior.

For example:


print(8/3) -> It will output floating-point number.

In order to print the int type of the result, we need to convert it to type int

print(int(8/3)) -> It will output int type number.

 Another way of getting the non-floating point number is using the floor division.

print(8//3) -> It will chop off the after decimals & will print int type.

 If you check its type, will show the result is of type int.

print(type(8//3))
class <int>

One more most used manipulation is a round function which rounds off the number.

Example:

 print(round(8/3)) -> It will output instead of printing 2.666666 will print out 3.

Using this function, we can also go a step further & decide the number of desired precision.
Suppose, if you want to round it to 4 We can write it as:

 print(round(8/3,4)) -> It will output 2.6667

 OR

 bill_per_person=99/4
 bill="{:.4f}".format(bill_per_person)

 OR

 bill_per_person=99/4
 print(f"Bill per person is: {bill_per_person:.4f}")

 Note: F-strings in python are used when we are in need of printing different types of data types                       altogether.

s=5.7
t=True

Syntax:
print(f" {s},{t}")

Example:


score=0-> int
height=1.8 ->float
is_Winning=True ->boolean
print("your score is" + str(score) + str(height) + str(is_Winning )
                🡇
 In place of this, we will be using a different manipulation which is the f-string.
                🡇
print(f"your score is {score}") ->It does all the conversions in the backend. You don't have to worry about this.

print(f"your score is {score}, your height is {height}, your is_winning ia {is_winning}") -> handling conversions of multiple data types

Output:
Your score is 0, your height is 1.8, your is_winning is True

It cuts down the manual labor of type conversions.  

7.
Python has different ways of writing mathematical calculations. Among them, I loved  s+=1 the most. It basically adds 1 to the value of the s and stores the end result back to s.

The second way of writing mathematical calculations:
 s=4+2 -> output: 2

That was all! Overall, it was an amazing day while learning all the above-mentioned 7 pointers. The course is really well structured and has a notch to keep working on it.

Thank You and will see you again in my next day update. I am planning to do it today itself.

Let's see!

Day 03: Python Learning with Angela Yu

Hey, I've decided to stick with Angela Yu's #100DaysofPython challenge. The course started with a warm welcome along with all the useful resources to stay motivated and always up with consistency. Since in success, each day step taken is more important.

So, therefore, took the pledge to continue this journey (staying consistent) no matter what & also marked my day 1 completion in the below image:

 This is Day 01 and here are my all the learnings:

1.  String Manipulation and code intelligence is the very first learning in python. 

a. The String Concatenation is done with the "+" sign.

    e.g. print("Hello " + "world")

b.  Be careful while writing code. There can be syntax errors if you make spelling mistakes, can be             indentation errors if 4 space indentation is not followed in Python.

     Luckily, now we have smart text editors which, do this job on our part and when you do any                 mistake it alerts "red vertical line".

Note: New lines can be created with a backslash and n. e.g: print('Hello\nWorld')

Output:

Hello

World

2. Input function is used to take inputs from a user. Once we hit run it prompts the user to input something.

Syntax:

input("Enter your name:")

e.g:

print("Hello" + " " + input("Enter your name:")")

output:

Enter your name: Kawal Preet Kaur

Hello Kawal Preet Kaur


Note: You can also calculate the no. of characters in your input using the len function.

Syntax:

user_input=input()
print(len(user_input))

#or

print(len(input())

Further, covered variable nomenclature which I had read in UNI time already.
All are somewhat similar to other programming languages.

In the end, the day ended with a project: band name generator which I
modified to generate a youtube channel name generator:


Thank You & See you again with the next day update!

Learning Python with Reeborg's World : Day 2

It's day 02. And, I am moving ahead with more interesting concepts in programming. I have decided today I am going to cover the most so, I could get a grasp on all the concepts at the earliest.

Day 02:

Well, how I planned & finalized today's study. It didn't go that way. I went out to solve reeborg's maze challenge that covers all that we learned yesterday. Seems like I need to work more hard on my problem-solving skills.

In the maze challenge, reeborg comes at random positions. I am able to solve most of all parts in a maze. Only, locations near to the corner of the maze I am facing a problem. As of now leading to a never-ending loop.

One more thing, 1002 is pretty dangerous in this world! Yes, true if you see 1002 without having a second thought; just go back to code review. 

In the attached screenshot you can see 1002 execution steps. Sadly, I am stuck at it and will be re-doing this challenge all over again. 

-> 1002 indicates a never-ending loop.



You can check out this challenge right here.

After this, I had moved to recursion and I understood it very well. Yet again for the second time today!!! Reeborg's recursion challenge made me realize: Honey, you're a novice :'( You can't learn python just by cramming concepts. Do more practice! HELL LOT OF PRACTICE.

In short, if we call out the definition of recursion then, it is:

Function calls itself repeatedly. If we're familiar with loops we can learn them easily. 

Syntax:

 def go_home():

    if not at_goal():

        move()

        go_home()


# now do it!

go_home()

You can try this code here under home1 challenge. I am on its counting on challenge. Have few doubts for them sent a mail to Andre Sir. Hopefully, I get a reply from him so, I can re-continue my python study.

For a brief introduction to recursion please go here.

Also, I am thinking to take an udemy course alongside. I am finding difficulty in tracking my progress since I am learning under no guidance. I will do my research for a good course in python and will share if I get myself enrolled in any.

In total, 3-4 hours went by just in these two tasks. However, I am happy I am being consistent on my journey.

Thank You.

Learning Python with Reeborg's World : Day 1

Today, I am on my journey with Reeborg's world as I really like the way how the combination of exercises & tutorials are structured so, one can really sign off after at least something in hand/mind.

So, Day 1 it is & is starting from Quick Python introduction, which has covered basics including definition, function syntax, function naming, etc.

Day 1:

1. Unlike, few programming languages Python Programs follow the flow of execution in the way they are written.

First, I have been introduced to 3 basic function callings:

move()

take()

put()

One makes the reeborg to move, the second instructs to take the object, and the third one orders reeborg to put the taken object.


Reeborg move take put function

2. Now, comes the main question what is a function?

In simple words, a function is a set of instructions for performing actions and is stored for later use.

Syntax of the function:

def non_keyword_function_name:

......useful statements


Note 2.1: Valid function names can start with a letter or underscore but, not with a number.

Note 2.2: Def is a keyword used to define a function/to show the starting of the function precede by a colon. Colon starts the body of the block which constitutes executable instructions. Make sure to indent the statements after the colon.

Note 2.3: Indentation is there to make the program more human-friendly or say to increase the program readability.

3. Now, wrote the first useful python program. By default, reeborg doesn't have a function to switch to turn right. So, here we go with our first square program. Additionally, I have created turn around function so, I can end the square at the position it first started. P.S. Just added to explore.

#created turn around & turn right function


def turn_around():

    turn_left()

    turn_left()


def turn_right():

    turn_left()

    turn_left()

    turn_left()


turn_left()

move()

turn_right()

move()

turn_right()

move()

turn_right()

move()

turn_around()


You can also try to create your own square at the link or can test the code here(click me).

In short, a function is a code that is written so, we can use & re-use when in need. It shortens human efforts. And, can be invoked/called just this way: function_name()


Note 3.1: Parenthesis [one is opening ( and another one is closing ) ] at the end while calling the function is important else function won't get executed. 

Note 3.2: In Python, the technically correct term for “thing” is object; for Python, everything that it knows is an object. e.g: s= 2+6

4. Third is Most used & helpful when it comes to writing repetitive code. That is For loop that allows executing specific instructions which are continually repeating & following the same pattern. For loop is used when you're known to no. of instructions to run. It's the safest loop if you wish to avoid infinite loops.

For instance, while writing the instructions for the turn_right() function. We had to re-write turn_left() as we were in need of 3 repetitive left turns to make it a right turn.

Herein, for loop can save the re-writing efforts.

Syntax:

def turn_right():
......for save_energy in range(0,3): #it will run from 0 to 2. Yeah, not including 3.
...............turn_left()

In this simple case, the code block to be repeated is a single statement.

Note 4.1: Inside range the loop doesn't run fully. As if you've written 0, 3. That means, will run from 0 to 2, not including 3. 

5. When we deal with data then, a need for conditions comes. For this purpose, in python, we have, if-elif-else

Syntax:

if condition:
.....pass
elif condition:
.....pass
else
.....pass

When you're to indicate a condition in negation, not keyword is used. It reverses the value. For example not True -> It will make the true statement False.

Note 5.1: It is not compulsory to write if-elif-else in a pair. You can write just if as well. But when there are two statements then, you can choose whether if-elif or if-else pair.

Note 5.2: Else comes only once for one/particular if block but under if, elif can be numerous.

6. We have one more looping option to deal with repetition. That is while loop. This loop runs until the particular condition becomes true. It's the wildest loop that can sometimes lead to an infinite loop/never-ending loop.

Syntax:

while condition_which_runs _until_it_is_true:
...........pass

Loop will be running over & over by the time you do not reach the true condition.


For a brief introduction to reboorg's python section 1 please refer here.

python hello.py File "", line 1 python hello.py ^ SyntaxError: invalid syntax

 Error: python hello.py File "<stdin>", line 1 python hello.py ^ SyntaxError: invalid syntax while running a python script in command prompt ( windows )


Possible Reasons: 

  1.  The problem is that you are trying to run python hello.py from within the Python interpreter, which is why you're seeing the traceback.
  2. You are not using the command prompt in administrator access.
  3. You are not in the right directory where your python files exist.

Solution: ( OS: Windows 10 )

Step 1: If you are using Windows, press Win+R and type cmd. As shown in the image below. And run it as administrator.


Step 2: Suppose in your computer, hello.py file is at this address: c:\users\yourname\desktop\pythonfiles

So, use the below-mentioned commands to go at the above-mentioned path.

C:\WINDOWS\system> cd..

C:\Windows>cd..

C:\Users>cd users\yourname\Desktop\

C:\Users\engineerbae\Desktop> cd python files

If you're already on the correct path directly jump to step 3.

Step 3: Now, run the hello.py this way: python hello.py in the command prompt.

You shall receive your output :)


Lately, when I ran my first python script using the command prompt. I had been using an interpreter directly and had no clue what's going wrong. 


Hope it helped.

Thank You!