Foundations of Python

75 / 134

Basic Building Blocks of Python

Overview

  1. Loops and Iteration: for, while
  2. Strings
  3. Files

Recording of Session

Slides

Code Repository for the course on GitHub



No hints are availble for this assesment

Answer is not availble for this assesment

Please login to comment

347 Comments

Hello ,

Can you please provide the right code for stock market problem to get maximum profit ?

 

  Upvote    Share

Hi Chilukuri,

You will learn better if you try to code on your own.

  Upvote    Share

what am I doing wrong? I ran this code to open a file which is at "https://jupyter.e.cloudxlab.com/user/rahulkhanna1617355/files/mbox.txt"

handle=open("mbox.txt")

how python is unable to detect the file. I also passing "/files/mbox.txt" but still got same error. Can you advise please?

 

---------------------------------------------------------------------------
FileNotFoundError                         Traceback (most recent call last)
<ipython-input-23-5e906220839f> in <module>
----> 1 handle=open("mbox.txt")

FileNotFoundError: [Errno 2] No such file or directory: 'mbox.txt'
  Upvote    Share

Hi Rahul,

You need to provide the path of where the file is located in your file system. For that, you can log in to the web console at https://cloudxlab.com/my-lab. In the web console, navigate to the location where you expect to find the "mbox.txt" file. Make sure you're in the correct directory where the file is stored.

To get the complete path of the file, you can use the 'pwd' command. This command will display the current directory's full path.

With the current working directory path in hand, you can create the complete path to the file "mbox.txt" by appending it to the current working directory. If, for example, the output of pwd is "/home/rahul/", then the complete path to the file would be "/home/rahul/mbox.txt".

Note that, you go through Linux basics once to get a better understanding of Linux file system.

 2  Upvote    Share

Is the following code correct for max profit from stock sales? ( I took 10 days for simplicity)

 I got a profit of 633 with a buying price of 334 and a selling price of 967

import random
stock_values=random.sample(range(0,1000),10)

min_value=1001
max_value=0
max_profit=0
for i in range(0,len(stock_values)-1):
    for j in range(1,len(stock_values)):
        if  stock_values[j]-stock_values[i]>0:
            profit=stock_values[j]-stock_values[i]
            max_profit=max(profit,max_profit)
            min_value=min(stock_values[i],min_value)
            max_value=max(stock_values[j],max_value)
print(max_profit)
print(min_value)
print(max_value)

 

The random list of stock_values is: 

 

  Upvote    Share

This comment has been removed.

count = 0
for i in fhandle :
    count = count + 1
print('Line count :', count)

I have a doubt. Within the fhandle context, I'm curious about how the iteration variable, denoted as ' i ' in this case, effectively keeps track of  only the "line count".

Specifically, I'm wondering how this iteration variable distinguishes whether its purpose is to count the number of lines and  not to count the number of "words " within a line, or the number of "letters" within a word. Could you shed light on this aspect?

  Upvote    Share

Hi Rajat,

The code you provided uses a loop to iterate through each line in the `fhandle` file handle, and it increments the `count` variable for each line. The variable name `i` is used as a common convention for an iteration variable, but you can use any valid variable name you prefer. The choice of variable name doesn't impact what's being counted; it's the way the loop is structured and what you're doing within the loop that determines what's being counted.

In the code you shared, the loop iterates through each line in the file (`fhandle`). It doesn't do anything with the individual characters or words within each line. The purpose of this loop is solely to count the number of lines in the file.

To clarify:

- If you wanted to count the number of words within each line, you would need an additional loop to iterate through the words within each line.

- If you wanted to count the number of characters (letters, numbers, symbols) within each line, you would need to iterate through each character within each line.

The specific behavior of what you're counting is determined by how the loop is structured and what you're doing inside the loop. In the code you provided, the loop iterates through lines, and the `count` variable is incremented for each line, effectively counting the number of lines in the file.

  Upvote    Share

How is it working exactly? How is it counting lines when 'a' is present in many words inside the text of the file

 

  Upvote    Share

Hi Kanishk,

The code is using a loop to go through each line (or item) one by one. The variable 'a' is used to represent each individual line as the loop goes through them. So, when the loop runs, 'a' takes on the value of the current line that the loop is looking at. This way, the code is able to count how many lines are in the book by going through each line one by one and increasing the 'count' variable by 1 each time. So, even if the word 'a' appears in the lines of the book, it won't affect the counting process because 'a' is just being used as a temporary way to refer to each line as the loop works through them.

  Upvote    Share
import random
def rand_list():
    x = []
    for i in range(1,366):
        x.append(i)
        x[i-1] =random.randint(0,100)
    return x
prices = rand_list()
mins=min(prices)
maxs=max(prices)
for buy in rand_list():
    if buy<mins:
        mins = buy
print("Min", mins)
for sell in rand_list():
    if sell>maxs:
        maxs = sell
print("Max",maxs)
print("max profit" , buy - sell)

Is this alright? because the output comes out to be :

min = 0 , max = 100 and max profit = 17

  Upvote    Share

import time
a = input("Hello")
timestamp = time.strftime('%H:%M:%S')
print(timestamp)
timestamp = time.strftime('%H')
if(int(timestamp)>=5 and int(timestamp)<12):
    print("gudmorning")

elif(int(timestamp)>12 and int(timestamp)<=17):
    print("goodafternoon")

elif(int(timestamp)>17 and int(timestamp)<=22):
    print("goodevening")

else:
    ("good night")

 

 

Hey Shubh

Please help me on this promgramme .i don't know what is my mistake.

 

  Upvote    Share

 Hi,

What error are you getting?

  Upvote    Share
for item in ["apple", "banana", 3, 4]:
  File "<ipython-input-10-861539b0de94>", line 1
    for item in ["apple", "banana", 3, 4]:
                                          ^
SyntaxError: unexpected EOF while parsing

 

why this error

  Upvote    Share

You need to put some statements inside the for loop. Otherwise it will throw this error.

  Upvote    Share

does the word 'line' have a special meaning for python?

  Upvote    Share

Can you further elaborate your doubt?

  Upvote    Share
import random
def rand_list():
    x=[]
    for j in range(1,366):
        x.append(j)
        x[j-1]=random.randint(0,100)
        
    return x
mins=365
maxs=0
for buy in rand_list():
    if buy < mins:
        mins = buy
print( "min", mins )
for sell in rand_list():
    if sell > maxs:
        maxs=sell
print( "max", maxs )
print('max profit: ',maxs-mins)

IS IT RIGHT? 

  Upvote    Share

Is Jupiter not working?

  Upvote    Share

Hi Nitin,

Jupyter is working. Are you facing any problem? 

If yes then please let us know so that we can assist you.

  Upvote    Share

when i type below code after creating atxt file'Frist.txt' and try to read the file it gives output as below and not the lines in the file, why ?

fh = open('Frist.txt')

fh

<_io.TextIOWrapper name='Frist.txt' mode='r' encoding='UTF-8'>

fh.read()

''
  Upvote    Share

Try using the print command to it.

  Upvote    Share

This comment has been removed.

buy_min = 100
sell_max = 0
stock=[10,8,5,4,1,2,3,4,5,6,7,8,9,10,18,7,7.5,9,10,12,15,16]
for price_buy in stock:
    if price_buy < buy_min:
        buy_min = price_buy 
print('minimum purchase price: ', buy_min)  
for price_sell in stock:
    if price_sell > sell_max:
        sell_max = price_sell
print('max selling price: ',sell_max)
print('max profit: ',sell_max-buy_min)

It's working alright. Any option to make it more efficient other than min max functions?

  Upvote    Share

Hi,

You can post this on our discussion forum using the below link and ask for peer feedback:

https://discuss.cloudxlab.com/

Thanks.

  Upvote    Share

#code for getting max profit and best buy and sell prices

stock=[10,8,5,4,1,2,3,4,5,6,7,8,9,10,18,7,7.5,9,10,12,15,16]
profit=0
buy_price=0
sell_price=0
for buy in stock:
    for sell in stock:
        if sell-buy > profit:
            profit=sell-buy
            buy_price=buy
            sell_price=sell
print("Max profit " + str(profit))
print("at buy price "+str(buy_price)+" and sell price "+str(sell_price))

  Upvote    Share

The below code is working fine for the stocks max profit question, any thoughts if this is an efficient way or is there any loophole in this :

x =[7,2.5,13,11,19,11,9,10]
min = 0
max = len(x) -1
y = sorted(x)
while (y[max] > y[min]) and (x.index(y[max]) < x.index(y[min])) :
    min = min + 1
print ("max_profit: ",y[max] - y[min])

  Upvote    Share

Hi,

This looks good to me. It would be great if you would share this on our discussion forum for further feedback from other learners. I have given the link to the same below:

https://discuss.cloudxlab.com/

Thanks.

  Upvote    Share

Sure, thanks

  Upvote    Share

This comment has been removed.

I did not understand.

 

at 2:03:40

 

if i want to what is the subject in the line 

 

then how can we extract the subject??

we have found the subjects but i want to know the content of that subject then how can we get it  ??

  Upvote    Share

This comment has been removed.

Hi Nirav,

This is a sample file that we created to demonstrate the number of lines which starts with the word "Subject:". Depending on the file you are using, you can read the rest of the text after subject line using other commands in Python.

Thanks.

  Upvote    Share

Sir,

I have a question regarding the execution of code shared by you:

CODE:

data = 'from stephen@uct.ac.za Sat Jan 5 2008'
atpos = data.find('@')
print(atpos)
sppos = data.find(' ',atpos)
print(sppos)
host = data[atpos+1 : sppos]
print(host)

 

My question is while finding the sppos variable we use ' ' (gap) and the variable 'atpos' as parameter. What does this mean? And also what if there is a gap before the position (which is 31 in this case) say at position 5 in this case. Why that space is ignored?

  Upvote    Share

Hi,

First, we find the location of the first occurance of the '@' character. This is at the 12th position.

Then, we find the first space from the '@' character. This is at the 22nd position from the beginning. This is given as:

sppos = data.find(' ',atpos), or sppos = data.find(character to fine,starting point)

Hope this answers your queries.

Thanks.

 1  Upvote    Share

That was really insightful. I got my answer. Thank You!

  Upvote    Share

Sir,

The audio of the recording of 'Basic Building blocks of Python' is having too much jitter and noise blocking (aslo the cloudxlab logo comes in and the ppt vanishes) some portions of the recordings. It sometimes is quite tough to understand. Please provide any transcript (or add a subtitle) if available because the inbuilt subtitles/closed captions don't act in those areas too.

Thank You!

  Upvote    Share

Hi,

Thank you for your feedback. We will consider these feedbacks while updating our courseware.

Thanks.

  Upvote    Share

Sir,

Regarding the stock problem. Is it that the user can buy and sell once in the whole 365 days? OR He can just buy the stock one day and sell them on the other day before buying a new stock (and this repeats for the whole 365 days)?

  Upvote    Share

Hi,

We are discussing one single stock here, you have it's values over a period of 365 days. You can buy once and sell once over that period of 365 days.

Thanks.

 1  Upvote    Share

Thank You, Sir.

  Upvote    Share

This comment has been removed.

iin code 126 range (1, 10) are these numbers considered to be a string by default???

  Upvote    Share

Hi,

Actually these are NoneType objects. NoneType is the type for the None object, which is an object that contains no value or defines a null value. You can check them using the type() command.

Thanks.

  Upvote    Share

how to count vowels in a word by using loops ?

  Upvote    Share

Hi,

You can try the following:

string=input("Enter string:")
vowels=0
for j in string:
      if(j=='a' or j=='e' or j=='i' or j=='o' or j=='u' or j=='A' or j=='E' or j=='I' or j=='O' or j=='U'):
            vowels=vowels+1
print("Number of vowels are:")
print(vowels)

Thanks.

  Upvote    Share

is this program is correct regarding stock_profit.

-------

def stock_profit(days):
    array=[]
    for i in range(1,days):
        array.append(random.randint(1,days))
    print(array)   

    largest=-1
    daycount=0
    largestday=0
    for j in array:
        daycount=daycount+1
        if  j>largest:
            largest=j
            largestday=daycount
    smallest=array[0]
    daycount=0
    smallday=1
    for j in array:
        daycount=daycount+1
        if j<smallest and daycount< largestday:
            smallest=j
            smallday=daycount

    netprofit=largest-smallest
    print("Largest number"+str(largest))
    print("Largest DAY"+str(largestday))
    print("smallest number"+str(smallest))  
    print("smallest day"+str(smallday))      
    print(largest-smallest)
    return netprofit

---

 2  Upvote    Share

in an example that sir mentioned he wrote

while True:

so what does this True stands for?

 1  Upvote    Share

Hi,

Good question.

This while-loop executes code repeatedly as long as a given boolean condition evaluates to True. Using while True results in an infinite loop.

Thanks.

 1  Upvote    Share

This comment has been removed.

IT is  showing error 

  Upvote    Share

i am waiting from yesterday still no got any solution

 

  Upvote    Share

Hi,

I could see that the path you mentioned here is of your local computer's. This Jupyter notebook can't access your local files, but only the files in your account on CloudxLab la. So makesure the file you mentioned in the path exists on the lab. Change the path accordingly.

Hope this helps.

Thanks.

  Upvote    Share

This comment has been removed.

sI ALREADY SAVED THE FILE THE THEN ALSO SHOWING ERROR

  Upvote    Share

Are you sure about the path of file?, if the file and notebook are in different direcotries then you have to specify the path of file along woth name.

Our default notebooks are in /home/<your-lab-username>/cloudxlab-jupyter_notebooks

  Upvote    Share

THEN WHAT SHOULD BE MY NEXT STEP

  Upvote    Share

Check path of file using files tab, and specify the path in code accordingly.

  Upvote    Share

I DO THAT THEN ALSO

  Upvote    Share

IT IS SHOWING ERROR

  Upvote    Share

Hi mayank,

That is 'l' not 'one'.

  Upvote    Share

instead of running code, showing new cells

running code, showing new cells

  Upvote    Share

Hi,

Once you run a code on the last cell, it will create a new cell automatically. And I can see that your codes are still running on 2 different cells. You need to let them complete running. I would suggest you to restart your server by following all steps from the below link, and then run the codes again, one cell at a time:

https://discuss.cloudxlab.com/t/im-having-problem-with-assessment-engine-how-should-i-fix/3734

Thanks.

  Upvote    Share

ok thanks

 

  Upvote    Share

but other ide it works

  Upvote    Share

Hello sir,

I am opening a text file and it is reading correctly. But for the line count program, it is not giving the correct result always. Sometimes It is showing the correct results though. I can't understand the issue. 

Sir, Please help.

  Upvote    Share

Hi,

Try creating the file using a text editor in Linux like nano. Also, please enter text instead of codes in the file.

Thanks.

  Upvote    Share

Ok sir, thank you.

  Upvote    Share

Not able to download the loops and iteration PPT. Please help

  Upvote    Share

Hi, 

You could click on the extended arrow icon on top right of required slide. This opens the slide in the new tab. Now you could download it using download icon on top right side.

Thanks.

  Upvote    Share

Hello All,

Can anyone from the forum please help me guide where the problem lies in reading the file for doing the 'count' assignment? 

Attached 2 screenshots. Any help will be highly appreciated.

Regards,

Shashwat

 

 

  Upvote    Share

Hi,

I have already replied to your previous comment. This is a new file that you are trying to read, please note that if it is the home directory then use the following path:

fhandle=open('../tmp.txt')

If is it within a folder named new_folder, use the following path:

fhandle=open('../new_folder/tmp.txt')

Hope this helps.

Thanks.

 1  Upvote    Share

Hi,

I am still unable to run this code as the jupyter is unable to read the file. Please suggest urgently as lot of time is getting wasted trying to figure out just the file aspect let alone te code.

Thanks for your help!

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

fhandle=open('reading_count.txt')
count_line=0
count_word=0
count_char=0


for text1 in fhandle :
    count_line=count_line+1
    text1.split()
    print(text1.split())       

    for text2 in text1.split() :
        count_word=count_word+1

    for text3 in text1 :
        count_char=count_char+1


print('The count for lines in the text: ',count_line)
print('The count for words in the text: ',count_word)
print('The count for total characters in the text: ',count_char)

 

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

FileNotFoundError                         Traceback (most recent call last)
<ipython-input-36-d2b564517085> in <module>
----> 1 fhandle=open('reading_count.txt')
      2 count_line=0
      3 count_word=0
      4 count_char=0
      5 

FileNotFoundError: [Errno 2] No such file or directory: 'reading_count.txt'
  Upvote    Share

Hi,

Try the following path:

fhandle=open('../reading_count.txt')

Thanks.

  Upvote    Share

This has now worked for me. Many thanks.....

Appreciate your quick help.

Regards,

Shashwat

 

  Upvote    Share

Screenshot of file location

  Upvote    Share

Hi Rajtilak,

I saved the files at the location below:

https://jupyter.f.cloudxlab.com/user/shashwatv8093/edit/reading_count.txt#

Regards,

Shashwat

 

 

 

 

  Upvote    Share

Hi,

This is the URL of the file, not the location. From the screenshot above, I can see that you have saved the file in your home directory. You do not need to specify any path if both the file and the Jupyter notebook are in the home directory.

Thanks.

  Upvote    Share

Hi,

I am facing issues reading the .txt file for doing the count. Could you please help guide how to find the relative path. The location where I saved the file is:  "https://jupyter.f.cloudxlab.com/user/shashwatv8093/edit/reading_count.txt#"

I am still getting the error: 

FileNotFoundError: [Errno 2] No such file or directory: 'reading_count.txt'

Please help suggest the resolution.

Thanks & regards,

Shashwat

 

 

 

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

 

 

---------------------------------------------------------------------------
FileNotFoundError                         Traceback (most recent call last)
<ipython-input-36-d2b564517085> in <module>
----> 1 fhandle=open('reading_count.txt')
      2 count_line=0
      3 count_word=0
      4 count_char=0
      5 

FileNotFoundError: [Errno 2] No such file or directory: 'reading_count.txt'

In [ ]:

  Upvote    Share

Hi,

Please share a screenshot of the location where you saved the file.

Thanks.

  Upvote    Share

This comment has been removed.

Hi sir,

My work is not getting saved in the jupyter. Please help.

  Upvote    Share

Hi Anuradha,

What error you're getting while saving?

Also i would like to tell you that we have different notebooks for different playlists so there might be chance that you're looking at a different notebook but all the notebooks are in your home directory only so you can open them any time by going to Jupyter from My lab page.

  Upvote    Share

Normally the work get auto saved but today neither its getting auto saved nor in save & checkpoint option.

  Upvote    Share

Hi Anuradha,

The notebook(foundations_of_python_450) was of around 12.8 MB because of an infinite loop in one of cell, I have commented the code in that cell now it should work fine.

  Upvote    Share

Yes sir, thank you

  Upvote    Share

Hello Team,

I tried the question related to getting maximum profit from stocks. I created a list of stock values using random function in a FOR loop. The below program gives me the desired output.

But, the FOR loop creates a list of 16 values even though I have mentioned the range of 0-10.

Can you please help me understand this difference?

Thanks,

Subh.

import math
import random
for x in range(0,10):
    stock[x]=int((random.random())*100)
days=(len(stock))-1
i=0
maxim=-1
while i<=days:
    j=i+1
    while j<=days:
        if maxim<(stock[j]-stock[i]):
            maxim=stock[j]-stock[i]
            buy=stock[i]
            sell=stock[j]
        j+=1
    i+=1
print(buy, sell, maxim)
print(stock)
print(days)
Caption

 

  Upvote    Share

Hi,

Try the following code instead:

import math
import random

stock = []
for x in range(0,10):
    stock.append(x)

Thanks.

 2  Upvote    Share

It works now. Thanks.

  Upvote    Share

Hi,

I was trying in web console for exercises, that is working fine. But I think the system is not taking those results into considerartion and throughing error . Can you help me to fix the problem 

Regards

Meenakumar

  Upvote    Share

Hi,

Would suggest you try in jupyter notebook and then submit. 

Thanks.

  Upvote    Share

Jupiter notebook is not at all getting connected.

 

Kindly suggest

Regards

MEena

  Upvote    Share

Hi,

Would request you to click on the control panel option, stop the server, then start the server, and refresh your page. Hope this helps.

Thanks.

  Upvote    Share

Hi Meena,

Sure i would like to help you, can you please share screenshot of error along with code you're submitting?

  Upvote    Share

Please help to understand when we open file using handle how it is assigned to it for example like a string or list second query, when we count the rows using for loop lile

for line in handle

How it comes to know tat the line ended!!

Thanks 

  Upvote    Share

Hi,

For your first query, we assign it to a variable. As for your second query, there is always a End-of-Line character present.

Thanks.

  Upvote    Share

Hell Rajtilak, Just want to undertand how it read through when we assign file to a variable. 

Like for example if I would like to search a particular string than what goes behind the logic !!

Thanks

  Upvote    Share

Assignment on reading line, words and characters in file:

prac=open('Practice.txt')
l=0
w=0
c=0
for line in prac:
    l+=1
    line.strip()
    word=line.split()
    w+=len(word)
    c+=len(line)
print('Line Count:',l)
print('Word Count:',w)
print('Character Count:',c)

Is it okay ?

 

Thanks.

  Upvote    Share

Hi,

The best way to assess your code is to run it on the lab. I would suggest create a file with that name, and then test your code on the same to check if it is working fine.

Thanks.

  Upvote    Share

Why the difference between the output of the string x and a ?

Thank you.

 1  Upvote    Share

Hi,

Good question!

This is because when you are providing an input, it is considering the entire input as a string. However, for the variable 'a', it is considering \n as a special character, newline.

Thanks.

  Upvote    Share

I've registered for the IIT Roorkee course on ML. Is this a fully recorded course ? Still wondering how it would different from multiple youtube courses which are available for free? Can't we have any Q&A sessions?

  Upvote    Share

Hi,

This is different because of a number of reasons. First, we not only provide lecture videos, but assessments, MCQs for you to practice your skills on. Second, these assessments are auto evaluated, and almost all of them have hints and answers associated with them, so you do not need to wait for someone to manually evaluate your codes and give you feedback. Third, we provide you the lab. You can work on your code without having to install anything, all you need is a browser and an internet connection. Fourth, we have a dedicated team of SMEs who assist you with your queries. Fifth, we have a discussion forum where you can post your query, or submit your code for peer review/feedback.

Thanks.

  Upvote    Share

Can you help me access the discussion forum ? Thanks.

  Upvote    Share

Hi,

Please access the discussion forum using the below link:

https://discuss.cloudxlab.com/

Thanks.

  Upvote    Share

Why such a strange result? 

Thanks

  Upvote    Share

This is because a is a list of int or integers. Hope this helps.

  Upvote    Share

why am I getting this error in almost all custom function?
also, in this string operation as well.

  Upvote    Share

Hi,

Could you please share a screenshot of your code with the error that you are getting.

Thanks.

  Upvote    Share

PFA

  Upvote    Share

PFA

  Upvote    Share

Hi,

Both of these issues are caused because of different reason:

1. Python is a case sensitive language. There are 2 variables in this code, Word and word, please change the case of either or them and the code should run fine.

2. You need to run the cell with the function first before you call it.

Thanks.

  Upvote    Share

could give give eg of find() with syntax

  Upvote    Share

Hi,

Please go through the below link for a detailed explanation:

https://www.geeksforgeeks.org/find-command-in-linux-with-examples/

Thanks.

  Upvote    Share

can python be used for finanacial analysis

  Upvote    Share

Hi,

Python is a versatile language which has application in diverse fields including financial analysis.

Thanks.

  Upvote    Share

why "Big">"small"  gives output false

  Upvote    Share

Hi,

This is because lower case ASCII characters have higher values than upper case ones.

Thanks.

  Upvote    Share

plz explain return function and break function in an easier manner

  Upvote    Share

Hi,

return and break are not functions, but commands/keywords. return helps in passing values from a function to the main function which called this function. break helps to get out of a loop prematurely.

Thanks.

  Upvote    Share

sir could you ellaborate retuen a bit more with eg as i am not getting the usage of return 

  Upvote    Share

Hi,

Sure! Please go through the below link for a detailed explanation of the same with examples:

https://www.w3schools.com/python/ref_keyword_return.asp

Thanks.

  Upvote    Share

how is 

"is" stronger than ==

  Upvote    Share

Hi,

I am sorry but I am unable to understand your question, could you please elaborate a little more?

Thanks.

  Upvote    Share

Sir, I ran the infinite while loop shown in the video. Afterwards deleted it also. But now I am not able to run any code. It shows waiting . [*] . How to solve this problem. Please help me.

  Upvote    Share

Hi,

Please delete the cell with the infinite loop by selecting the cell and clicking on x in your keyboard.

Thanks.

 1  Upvote    Share

Thanks a lot sir.

  Upvote    Share

How can we reverse a given list by slicing.

  Upvote    Share

You can directly use reverse() method on list object

such as 

li = ['a','b','c']

li.reverse()

print(li) # It will print like 'c', 'b', 'a'

  Upvote    Share

I have added mbox.txt.

Bu while type code fhandles = open("mbox.txt"), It is showing error no such file or directory.

  Upvote    Share

Hi,

You need to specify the full/relative path to the file.

Thanks.

  Upvote    Share

How to give the full / relative path. 

  Upvote    Share

Hi,

You will find more about this in assignment number 104 of this same topic. You can also go through the below link for more details:

https://stackoverflow.com/questions/918154/relative-paths-in-python

Thanks.

  Upvote    Share

Hi Team

Please help me in following situation when  file placed in following location:

https://jupyter.f.cloudxlab.com/user/nikhilkulshrestha044617/files/mbox.txt

fhandle = open('files/today.txt')

The following error is shown

---------------------------------------------------------------------------
FileNotFoundError                         Traceback (most recent call last)
<ipython-input-6-68db0fc23d1c> in <module>
----> 1 fhandle = open('files/today.txt')

FileNotFoundError: [Errno 2] No such file or directory: 'files/today.txt'

  Upvote    Share

Hi,

You must understand that these Jupyter notebooks are files too and have been place in certain location. So, if you are addressing your file with a relative path, that relative path should be with resepect to this Jupyter notebook. Otherwise, you can simply give the complete path to the file.

Thanks.

  Upvote    Share

Great learning. Could you pls add an example snippet for indefinite loop please.

  Upvote    Share

Hi,

Thank you for your appreciation and your feedback. We will keep this in mind for our future updates.

Thanks.

  Upvote    Share

I have a question.

I tried this code. It exectues but why it print the list of numbers in two vertical line?

Below is my code:

largest_so_far=1
print ('Before', largest_so_far)
for the_num in [9,15,87,42,94,16]:
    if the_num >largest_so_far:
        largest_so_far = the_num
    print(largest_so_far, the_num)
print ('After',largest_so_far)

 

Before 1
9 9
15 15
87 87
87 42
94 94
94 16
After 94
  Upvote    Share

Hi,

This is because of the print statement that you have used:

print(largest_so_far, the_num)

Thanks.

  Upvote    Share

Im getting this type of while executing file 

  Upvote    Share

Hi,

This is a part of which assessment?

Thanks.

  Upvote    Share

Hi

All of a sudden. When I execute shift enter  in ClouldEx lab , the code is not getting executed. It inserts new cell. Even when I press run it is not working.

Do you know how to solve it. 

 

Thanks
Kalyan

  Upvote    Share

Hi,

Please restart your server by following the steps from the below link:

https://discuss.cloudxlab.com/t/im-having-problem-with-assessment-engine-how-should-i-fix/3734

Thanks.

  Upvote    Share

#COUNTING LINES, WORDS & CHARACTERS IN A TEXT FILE:

fhandle=open('mbox.txt')
count_line=0
count_word=0
count_char=0


for text1 in fhandle :
    count_line=count_line+1
    text1.split()
    print(text1.split())       

    for text2 in text1.split() :
        count_word=count_word+1

    for text3 in text1 :
        count_char=count_char+1


print('The count for lines in the text: ',count_line)
print('The count for words in the text: ',count_word)
print('The count for total characters in the text: ',count_char)

 

OUTPUT:

 

['This', 'is', 'a', 'line.']
['This', 'is', 'another', 'line.']
['3rd', 'line', 'is', 'an', 'exception.']
The count for lines in the text:  3
The count for words in the text:  13
The count for total characters in the text:  63
  Upvote    Share

Hi,

Are you facing any challenges here?

Thanks.

  Upvote    Share

Can we change a particular word in text file with replace(), after opening the file with open() and then print the desired result in output?

  Upvote    Share

Hi,

Yes you can.

Thanks.

  Upvote    Share

How?

I tried this, ouput was not what i expected. Kindly correct if something is missing :

fhandle=open('mbox.txt')
for q in fhandle:
    if q.startswith('3rd'):
        q.replace('3rd','This')
    print(q)

OUTPUT:

This is a line.

This is another line.

3rd line is an exception.

 

Thanks.

 

  Upvote    Share

Hi,

We do not have the provision for manually checking assessments. You can post this on our discussion forum at the below link and ask for feedback from your peers:

https://discuss.cloudxlab.com/

Thanks.

  Upvote    Share

What is "Ignore case" that is being talked at 1:40:40?

Kindly explain.

Thanks.

  Upvote    Share

Hi,

Here we are discussing how we can identify the line that starts with a letter irrespective of it's case, i.e. whether it is lowercase of capitalized.

Thanks.

  Upvote    Share

for countdown in [5,4,3,2,1]:
    n=countdown
    if n>0:
        print ('.')
        n=n-1
    print(countdown)
print ('blastoff')

Why the dot is displayed as many times as n for this code

  Upvote    Share

Hi,

This is because you are printing the dot as many times as the loop is being executed.

Thanks.

  Upvote    Share

Hi,

How do we take array as a user input for doing smallest/largest(for example) no operations on them?

Thanks.

  Upvote    Share

Hi,

This an example to print the ’N’ number of input array:

number_array = list()
number = input("Enter the number of elements you want:")
print ('Enter numbers in array: ')
for i in range(int(number)):
    n = input("number :")
    number_array.append(int(n))
print ('ARRAY: ',number_array)

Thanks.

  Upvote    Share

Hi ,

stocks_7=[5,2,8,9,12,10,11]
sum_val=sum(stocks_7)
average_val=(sum(stocks_7)/len(stocks_7))
length=len(stocks_7)
print(" Sum of all the  value in the array is" ,sum_val," with length of ",length," average value is : ",average)

  Upvote    Share

Hi,

Are you facing any challenges with this?

Thanks.

  Upvote    Share

def max_profit(x):
    number_of_stocks=float(input('Please enter number Of Stocks to buy :'))
    min_stock_val=min(x)
    max_stock_val=max(x)
    index_min = x.index(min_stock_val)
    index_max = x.index(max_stock_val)
    print("Minium stock price in 7 days is ",min_stock_val,"$ on day:" ,index_min+1 )
    print("Maximum stock price  in 7 days is ",max_stock_val,"$ on day:" ,index_max+1 )
    max_profit=(float(max_stock_val)*number_of_stocks)-(float(min_stock_val)*number_of_stocks)
    return max_profit
stocks_7=[5,2,8,9,12,10,11] # stocks price for last 7 days
print("You can make Maximum profit  if you buy stocks on day:",index_min+1 ," with price:",min_stock_val,"$ and sell on day:","index_max+1 with price:",max_stock_val,"$ with profit of ",max_profit(stocks_7),"$")

 

  Upvote    Share

Hi,

Are you facing any challenges with this?

Thanks.

  Upvote    Share

This comment has been removed.

This comment has been removed.

This comment has been removed.

Answer to the stock value question asked in the lecture. Is it correct?

#stock_values[1, 3, 1.5, 6, 7, 5, 4] taking for 7 days.
stock_values = [1, 3, 1.5, 6, 7, 5, 4]
smallest_so_far=min(stock_values)
largest_so_far=max(stock_values)
for profitable_buy in stock_values:
    if profitable_buy == smallest_so_far:
        print("Profitable buy will be ", profitable_buy)
for profitable_sell in stock_values:
    if profitable_sell == largest_so_far:
        print("Profitable sell will be ", profitable_sell)

        max_profit = largest_so_far - smallest_so_far
print("A stock share bought at", smallest_so_far, "and sold at", largest_so_far, "will yield the maximum profit of", max_profit)

  Upvote    Share

Hi,

Are you facing any challenges with this?

Thanks.

  Upvote    Share

stockvalue = [1,1.5,60,7,300,9] #taking 7 days
maxprofit = 0
for ilist in range(0,len(stockvalue)):    
    for jlist in range(ilist,len(stockvalue)):
        profit = stockvalue[jlist] - stockvalue[ilist]
        if(profit > maxprofit):
            maxprofit = profit
            buyprice = stockvalue[ilist]
            sellprice = stockvalue[jlist]

print(maxprofit,buyprice,sellprice)

  Upvote    Share

Hi,

Are you facing any challenges with this?

Thanks.

  Upvote    Share

i haven't understood this......can u explain i detail

  Upvote    Share

Hi,

This video contains several topics. Could you please tell me which of these topic were you not able to understand.

Thanks.

  Upvote    Share
for i in range(0,10):
    print(i,end="")

end="" is used for printing output in a single line 

output : 0123456789

if we remove end="" in print then 

output : 

0

1

2

3

4

5

6

7

8

9

 

 

  Upvote    Share

Hi,

Are you facing any challenges with this?

Thanks.

  Upvote    Share

Hey , If I will use below script.

for countdown in [6,5,4,3,2,1]:
    print(countdown)
print('blastoff')

6
5
4
3
2
1
blastoff

 

BUT if I run 

for countdown in [6,5,4,3,2,1]:
    print(countdown)
    print('blastoff')

 

6
blastoff
5
blastoff
4
blastoff
3
blastoff
2
blastoff
1
blastoff

 

Why ?

 

Thanks.

  Upvote    Share

he indentation in Python is very important. Python uses indentation to indicate a block of code.

for countdown in [6,5,4,3,2,1]:

    print(countdown)
    print('blastoff')

in the above code print('blastoff') is coming under the for loop block so it will print it will print on each time .

for countdown in [6,5,4,3,2,1]:
    print(countdown)
print('blastoff')

here see the space before print('blastoff') , it is not under the  for loop block   so after finishing the for loop  it will

print only ones 

hope you gt the logic 

  Upvote    Share

Hi,

Because in the second case both the print statement are inside the loop, so every time the control traverses the loop, both of them are executed.

Thanks.

  Upvote    Share

i ithink i solve the problem, dont know whether it is correct or not

baray=[108, 435, 220, 25, 50, 579, 382, 96, 316, 83, 535, 229, 342, 88, 481, 228, 282, 149, 71, 484, 62, 319, 259, 196, 482, 20, 477, 68, 412, 529, 477, 172, 364, 195, 360, 306, 155, 509, 450, 527, 11, 156, 459, 444, 294, 376, 553, 319, 432, 554, 486, 236, 210, 557, 29, 233, 467, 4, 80, 584, 360, 518, 511, 158, 68, 518, 504, 6, 296, 298, 77, 189, 280, 240, 99, 46, 45, 109, 69, 45, 410, 404, 375, 49, 546, 523, 370, 174, 363, 221, 98, 264, 179, 223, 299, 598, 462, 51, 200, 313, 492, 342, 396, 342, 300, 232, 20, 528, 473, 160, 320, 30, 307, 332, 36, 293, 294, 141, 558, 108, 368, 322, 176, 545, 228, 300, 219, 532, 289, 378, 330, 133, 460, 433, 243, 236, 545, 363, 298, 330, 336, 360, 280, 157, 320, 99, 93, 116, 3, 398, 172, 162, 457, 191, 418, 195, 500, 98, 128, 555, 48, 75, 27, 447, 120, 515, 302, 137, 394, 175, 21, 305, 100, 150, 386, 158, 60, 115, 378, 104, 229, 140, 442, 278, 141, 343, 577, 235, 148, 146, 180, 189, 435, 270, 157, 212, 300, 179, 303, 190, 128, 508, 568, 82, 402, 376, 191, 18, 166, 428, 437, 20, 460, 477, 225, 83, 506, 340, 305, 435, 7, 156, 421, 341, 487, 281, 275, 191, 419, 253, 591, 177, 472, 60, 7, 309, 366, 593, 79, 116, 29, 568, 249, 201, 6, 526, 283, 131, 48, 61, 171, 508, 326, 147, 167, 199, 155, 103, 70, 574, 297, 340, 300, 220, 586, 361, 376, 201, 286, 129, 13, 149, 489, 410, 558, 530, 51, 139, 371, 372, 164, 308, 414, 500, 55, 542, 330, 337, 271, 454, 209, 292, 383, 466, 311, 122, 148, 182, 152, 167, 314, 264, 195, 205, 345, 451, 353, 127, 391, 326, 51, 536, 594, 197, 590, 417, 532, 172, 243, 595, 498, 534, 153, 531, 59, 97, 255, 326, 224, 311, 517, 505, 211, 247, 366, 340, 407, 435, 15, 237, 499, 587, 408, 568, 262, 459, 516, 314, 398, 102, 410, 81, 36, 170, 149, 408, 160, 104, 223, 571, 365, 565, 455, 477, 2]

y=0
k=0
near=[]


for x in baray:
    y=y+1
    for i in baray[y:]:
        if (i-x) >0:
            near.append(i-x)
    
k=max(near)
y=0


for x in baray:
    y=y+1
    for i in baray[y:]:
        if (i-x) == k:
            datebuy=baray.index(x)+1
            datesell=baray.index(i)+1
            print("\nThe Buying value =",x,"Thousand (On",datebuy,"Day)" )
            print("\nThe Selling value =",i,"Thousand (On",datesell,"Day)")
            print("Profit= ",k,"Thousand")
            break

answer is like this


Question 
  Upvote    Share

Hi,

Would request you to post this on our discussion forum at the below link for feedback:

https://discuss.cloudxlab.com/

Thanks.

  Upvote    Share

Doubt regarding multiple dots in countdown example

Hi Team,

Sandeep said this is because we are using while loop. But, if commands are,

print(".")

then, n= n-1 

and lastly print( countdown)

This must give an output similar to,

dot

1

2

3

4

5

dot

1

2

3

4

......

 

 

  Upvote    Share

Hi,

Could you help me with the code that you are referring to?

Thanks.

  Upvote    Share

Hi, PFA 

for countdown in [5, 4, 3, 2,1 ]:
    n = countdown
    while n > 0:
        print(".")
        n = n - 1
    print(countdown)
print("Blastoff")

  Upvote    Share

Hi,

So are you facing any challenges with this?

Thanks.

  Upvote    Share

This comment has been removed.

as when we use for loop  it reads the single word at a time . but in this open() file case , when we are using the for loop its reading the complete whole line instead of reading the single word . how?

 

  Upvote    Share

Hi,

Could you please point out the code you are referring to?

Thanks.

  Upvote    Share

Hello CloudX team,

I created a file called 'myfirst.txt' and stored it in the root directory. When I enter the command - fhandle = open ('myfirst.txt'), this is the error message I receive:

---------------------------------------------------------------------------
FileNotFoundError                         Traceback (most recent call last)
<ipython-input-4-62db19f94b2b> in <module>
----> 1 fhandle = open ('myfirst.txt')

FileNotFoundError: [Errno 2] No such file or directory: 'myfirst.txt'

Could you please advice on how I can enter a path for the file if the default is not set to the root (which I would have assumed, maybe wrongly)?

Thank You.

  Upvote    Share

CloudX Lab team,

I did some research and used the 'os.getcwd()' command to check where the working directory was. Then I moved the file to that directory and did a 'path.exists ('myfirst.txt')' to ensure that the file was available.

And now it works :)

Thank You.

  Upvote    Share

Sir the way you teach is extremely spureb!!Salute to your efforts.You are better than foreign teachers .

  Upvote    Share

Hi,

Thank you for your feedback. Happy learning!

Thanks.

  Upvote    Share
Hi CloudX Lab Team:

Below error, I couldnt able to trace the path and the only detail I know this file exist is in the below path.

FileNotFoundError                         Traceback (most recent call last)
<ipython-input-18-f8d57e907599> in <module>
----> 1 fhandle= open('second.txt')

FileNotFoundError: [Errno 2] No such file or directory: 'second.txt'

 

File is in this path --> https://jupyter.e.cloudxlab.com/user/maruthishan8474/edit/second.txt

  Upvote    Share

Hi,

This is a part of which assessment?

Thanks.

  Upvote    Share

In the Parsing and Extracting example:
sppos=data.find(' ',atpos) it gives output as 31 but the first space in the sentence is after from which is 5.then why the output is 31.

  Upvote    Share

Hi,

This is because we are specifying the starting point as 21. If you look at the statement below:

sppos = data.find(' ',atpos)

We have given atpos (which is 21) as the starting point. So it finds the first space from that position.

Thanks.

-- Rajtilak Bhattacharjee

  Upvote    Share

I have 2 queries:
1. In this I need to close and open file again and again to change mode. Can mode of opened file be changed?
2. Can on using write() it overwrites the content of file. So, can we append content to file ?

  Upvote    Share

Hi, Apoorva.

Good question.

1) Yes you can do it, if you use the reference object "file" is assigned to another file, but It is a good practice to use the close() method to close a file.

2) write() will completely overwrites the content of the file, to append you need to open it "append" mode using "a" as argument instead of "w".
All the best!

-- Satyajit Das

  Upvote    Share

In the while example:
a condition is written if line[0]=="#"....Here why do we use square bracket([ ])

even I using like this if line=="#" gives same result.Then what's the purpose of the square bracket?

  Upvote    Share

Hi Suman,
So in the line " if line[0]=="#" " it is actually checking for first character or string in variable 'line' and in the line " if line=="#" " it is checking for the complete value of variable.
Let me give a more clear example to you, please execute the below code in your notebook and see results,
list1 = 'sachin';
if list1[0]=='a':
print(list1[0])
if list1=='sachin':
print(list1[0])

If you see in the output, the first 'if' statement will be false because the first element of string is not 's' but the second 'if' statement is executed because the value of variable 'list1' is equal to string 'sachin'.
-- Sachin Giri

  Upvote    Share

def is_vowel(1):
return 1 in 'aeiou'

this code keeps returning an error if indentation.

  Upvote    Share

Hi,

Please check if you have indented the second line properly. Also, would request you to share a screenshot of your code.

Thanks.

-- Rajtilak Bhattacharjee

  Upvote    Share

Hi
Regarding files. i'm using filehandle.write to add lines in existing files. but it seems overwriting the file. How add line to existing file

rihand=open('SampleText.txt','w')
rihand.write('writing data into file')

  Upvote    Share

Hi,

This is because you are opening the file in write mode ('w' switch in open() function). Please open it in append mode by replacing the 'w' with 'a' and it should work fine.

Thanks.

-- Rajtilak Bhattacharjee

  Upvote    Share

Hi

what is use of double under score functions like __len__
could you some examples

Thanks,
Hari

  Upvote    Share

Hi,

Any method will double underscores like __this__ is meant for Python to call. You can find more information about them here:
https://stackoverflow.com/q...
Thanks.

-- Rajtilak Bhattacharjee

  Upvote    Share

Hello sir
How to do word count of a file?
Regards
Prithvi Kaushik

  Upvote    Share

Hi,

You can follow these steps to count the number of words in a text file:
Open the file in read mode and handle it in text mode.
Read the text using read() function.
Split the text using space separator.
The length of the split list should give the number of words.
You can refine the count by cleaning the string prior to splitting or validating the words after splitting.

Thanks.

-- Rajtilak Bhattacharjee

  Upvote    Share

we can print in one line using the following:
x = ' this is a test string'
print(x)
for i in x:
print(i, end = ' ')

  Upvote    Share

Hello sir
Can we say this if condition of continue statement is false, it continues to the next statement, else, it goes to the top of the loop?
Regards
Prithvi Kaushik

  Upvote    Share

Hi,

It depends on the code. Can you share a screenshot of the code you are referring to?

Thanks.

-- Rajtilak Bhattacharjee

  Upvote    Share

Sir I could not understand the question of the stocks profit, can you explain the question?

  Upvote    Share

Hi,

So let's assume you have the stock value of a particular stock for 365 days in an array. You can buy only once and then sell. So you need to find the particular value which will give you the maximum profit. How do we calculate the maximum profit? By maximizing the different between the buy value of the stock and the sell value of the stock. This might seem straight forward at first, but if you think about it, the minimum value in this array might not give you maximum profit. Let's take an example:

Let's say the minimum value in this array is 5, after that the stock reaches a maximum value of 12. So it gives me a profit of 7 (12 - 5). However, there may be another instance where the stock value was 20, which is way more than the minimum value, but after that the stock reached a value of 40, which gives me a better profit of 20 (40 - 20). So keeping this scenario in mind we need to find the best buy and sell value of the stock which would give me maximum profit.

Thanks.

-- Rajtilak Bhattacharjee

  Upvote    Share

The chapter 8 docs are not given

  Upvote    Share

Hi,

We have added the slides for Chapter 8. Could you please check and let us know if you can view them.

Thanks.

-- Rajtilak Bhattacharjee

  Upvote    Share

Thanks

  Upvote    Share

how to save the files in jupyter and upload it in github

  Upvote    Share

Hi Sagan,
The notebook gets automatically saved after every change and it can be downloaded on local by going of 'File' >>'Download as' present in menu bar.
-- Sachin Giri

  Upvote    Share

hi sir is there a possibility the you could start a discord channel ... it could prove to be very beneficial for the students subscribed to this course

  Upvote    Share

Hi Mangesh,
Thank you for your suggestions. We'll look into it and let you know if we start one. ????

-- Sachin Giri

  Upvote    Share

can you guide any Books or reference guides to learn "python" efficiently as i am confusing when doing tasks i have been given:
if so please share the URL of reference books or authors?

  Upvote    Share

Hi Ajay,

Thank you for contacting us.
Are you facing problems while doing the assessment of the course? Kindly share with us where are you facing trouble. If you just want to know books for the general-purpose we would recommend you to instead doing hands on as it will benefit you much more. Complete all the topics in our python course and you will definitely feel much confident. You can always take help from the hint and solution section to clear your doubts. Even the discussion forum is helpful in that regard.

Please feel free to let me know if you have any queries and I'll be glad to help.

Hope this helps.

Thanks.

-- Anupam Singh Vishal

  Upvote    Share

i am absolutely happier with the way course going on, and i am understanding the topics very well, although i am trying with different examples on my own,how ever when tasks or problems given,while writing code i am stuck some where on the code what to use where to use particular function or string.
Any possible resolution for this as it would be more benificial and learn python with effective pace.

  Upvote    Share

Ajay,

This blog has a list of books you can refer to. I can recommend the O'Reilly book.

https://realpython.com/best...

-- Praveen Pavithran

  Upvote    Share

Earlier i am receiving output as 0 however after restarting kernel and read the file i am getting error output please check and help.

  Upvote    Share

Hi,

The lines should start with 'Subject:' and not 'subject:', please note that Python is a case sensitive language.

Thanks.

-- Rajtilak Bhattacharjee

  Upvote    Share

hi i have got the output i re write the code, and executed successfully

  Upvote    Share

could you please share the URL of GitHub

  Upvote    Share

Hi,

Please find below the link to our GitHub repository for this course:

https://github.com/cloudxla...

Thanks.

-- Rajtilak Bhattacharjee

  Upvote    Share

Hello Team,

Kindly help on python question which as given for practice in session. please help to solve this, i am not able to find where i am stuck.

question:-
'''
you are given stock values in an array [1, 3, 2, 6, 7]
you can buy only once and then sell.
you need to find the max profit you can make.

'''

my code :-

price = [1, 3, 2, 6, 7]
mini= None
maxp = 0
for pp in [1, 3, 2, 6, 7]:
if mini is None:
mini = pp
print(mini)
if mini < price[pp]:
print('------1------')
print(maxp, price[pp], mini)
print('------2------')
maxp = maxp + price[pp] - mini
print(maxp, price[pp], mini)
print(maxp)

Expected output:- maxp = 7

my output flow is shown as below:-

5
1
------1------
0 3 1
------2------
2 3 1
2
------1------
2 6 1
------2------
7 6 1
7
------1------
7 2 1
------2------
8 2 1
8
---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
<ipython-input-73-bb7c9ffcb6a1> in <module>
9 mini = pp
10 print(mini)
---> 11 if mini < price[pp]:
12 print('------1------')
13 print(maxp, price[pp], mini)

IndexError: list index out of range

  Upvote    Share

Hi,

Would request you to share a screenshot of your code and the error that you are getting.

Thanks.

-- Rajtilak Bhattacharjee

  Upvote    Share

Hi Rajtilak,

please find attachment above and request to help on this.

Thanks & Regards

  Upvote    Share

Hi,

You cannot compare a tuple and an int. mini is a tuple, whereas price[pp] is an int.

Thanks.

-- Rajtilak Bhattacharjee

  Upvote    Share

Hi Rajtilak,

1st query:- could you please differentiate how can i differentiate tuple from list?

2nd query for below code , i have replaced mini with other variable smal but i am getting error like ' list index out of range' as shown below.

Kindly advise what changes should i make to run the loop so as to get desired output.

  Upvote    Share

Hi,

To answer your queries:

1. The key difference between a list and a tuple is the fact that lists are mutable whereas tuples are immutable. Also, A list has a variable size while a tuple has a fixed size.

2. Simply changing the name of the variable won't help. The type of object you are trying to compare is different. One is a list of numbers, the other one is just one number.

If you are stuck somewhere you can always take a hint, or look at the answer.

Thanks.

-- Rajtilak Bhattacharjee

  Upvote    Share

Closing ticket

-- Praveen Pavithran

  Upvote    Share

In the Counting lines , the code actually counts total number of string characters instead of counting lines. Please refer to the screenshot.

  Upvote    Share

Hi,

Would request you to try the following code:

fhand = open('ml/python/mbox.txt')
count = 0
for line in fhand:
count = count + 1
print(line)
print(count)

This would print the lines and not characters, this would also print the total number of lines.

Thanks.

-- Rajtilak Bhattacharjee

  Upvote    Share

what does 'if line[0]' means as shown in the screenshot

  Upvote    Share

Hi,

Here "line" is a list accepting input from users. line[0] is the first element of the list.

Thanks.

-- Rajtilak Bhattacharjee

  Upvote    Share

Hi All,

I have created a text file called as "small.txt" into the my login folder i.e.
/user/atulbioknoppix7078/small.txt

i am trying with below codes but i am facing same issue as no such file or directory.

txtfile_name = open("small.txt")
print(txtfile_name)

txtfile_name = open('small.txt','r')
print(txtfile_name)

txtfile_name = open('\user\atulbioknoppix7078\small.txt','r')
print(txtfile_name)

kindly guide me here

Regards
Atul

  Upvote    Share

Hi,

Would request you to share a screenshot of the location of the file, your code, and the error that you are getting.

Thanks.

-- Rajtilak Bhattacharjee

  Upvote    Share

I am trying to run this command fhandle = open("shaf.txt") but getting FileNotFoundError: [Errno 2] No such file or directory: 'shaf.txt' even though I have saved the file named shaf.txt in jupyter

  Upvote    Share

Where is the txt file supposed to be in computer?
Can the text file be anywhere in the computer?
I am using anaconda on my laptor

  Upvote    Share

Yes, file can be anywhere on the computer

  Upvote    Share

So if write mod.txt it shows file is not in directory. Why is it so?
what will be the syntax for the accessing other files

  Upvote    Share

Hi,

The syntax for accessing local file remains the same, only the path is represented as follows:

'C:\\User\\Folder\\file.txt'

You need to use double backslash instead of forward slash.

Thanks.

-- Rajtilak Bhattacharjee

  Upvote    Share

Thanks

  Upvote    Share

in lab it is always showing [*] sign . why ?

why it is always processing.
i want my codes to work

  Upvote    Share

Hi,

Are you trying to run any infinite loops? That may be causing the issue. If that is the case, I would suggest you to delete that cell containing that code and try again. If that is not the case then I would suggest you to follow all the steps given in the link below and try again:
https://discuss.cloudxlab.c...
Thanks.

-- Rajtilak Bhattacharjee

  Upvote    Share

why the code you are running in video is not running on lab .

  Upvote    Share

Hi Naman,

Thank you for contacting us.
Kindly be more specific, which codes are you unable to run in the lab? Please provide screenshots so we may be able to help you better.

Please feel free to let me know if you have any queries and I'll be glad to help.

Hope this helps.

Thanks.

-- Anupam Singh Vishal

  Upvote    Share

i am getting indentation problem ?
why it is occouring

  Upvote    Share

Hi Disqus,

Thank you for contacting us.
In python, there is a concept of differentiating a block of code by the same amount of whitespace, this is also known as indentation. It may be possible that correct indentation is not provided, check the code once again if you are unable to find any problem with it then you can share your screenshot with us so we may be able to figure out the problem.

Please feel free to let me know if you have any queries and I'll be glad to help.

Hope this helps.

Thanks.

-- Anupam Singh Vishal

  Upvote    Share

Hi,
Icreated a text file but now I am unable to open the file,

fhandle =open("mbox.txt")
fhandle

I am getting below error :
FileNotFoundError Traceback (most recent call last)
<ipython-input-37-03a09e9b1dea> in <module>
----> 1 fhandle =open("mbox.txt")
2 fhandle

FileNotFoundError: [Errno 2] No such file or directory: 'mbox.tx

Please suggest.

  Upvote    Share

Hi,

Would request you to go ahead and check if that has not been deleted, or if this is the name of the file.

Thanks.

-- Rajtilak Bhattacharjee

  Upvote    Share

Hi,
I have verified, file is still available with the correct name and its not deleted.
Thanks

  Upvote    Share

Hi Cloudx team,

Can you please help me in this?

Thanks,
Jyoti

  Upvote    Share

Hi,

Would request you to share a screenshot of your code, the error that you are getting, and the location of the file.

Thanks.

-- Rajtilak Bhattacharjee

  Upvote    Share

I had the same problem. I had to give the full path to read the file(/home/rohanmudaliar8380/testfile.txt). i think i need to set path to get over this. how do i do that

  Upvote    Share

@rohan0506:disqus thank you for the workaround

  Upvote    Share

Hi,

Would request you to share a screenshot of your code, the error that you are getting, and the location of the file.

Thanks.

-- Rajtilak Bhattacharjee

  Upvote    Share

facing same issue -

  Upvote    Share

i am also getting the same problem :(

  Upvote    Share

Hi Rajtilak,

Location of the file is : https://jupyter.f.cloudxlab...

Can you please share how to give complete file path?

  Upvote    Share

Hi Cloudx team,

Can you please help here. I am still not able to open the file.

  Upvote    Share

Hi,

Would request you to try the following code instead:

import os
file='/ml/python/mbox-short.txt'
path=os.getcwd()+file
fhandle = open(path)
fhandle

Thanks.

-- Rajtilak Bhattacharjee

  Upvote    Share

How to create a word or excel file in jupyter?

  Upvote    Share

Hi,

You cannot create a Wor/Excel file in Jupyter.

Thanks.

-- Rajtilak Bhattacharjee

  Upvote    Share

Then, how would i work on file?

  Upvote    Share

Hi,

Could you please tell me which assessment you are trying to attempt.

Thanks.

-- Rajtilak Bhattacharjee

  Upvote    Share

how do we use for loop in arithmatic progration of nth point?

  Upvote    Share

Hi,

Here is a little example:
https://www.geeksforgeeks.o...
Thanks.

-- Rajtilak Bhattacharjee

  Upvote    Share

The jupyter notebook is problematic.
I created a text file , and when I tried to open the file using the command:
fhandle = open('himangshu.txt)

I got FileNotFoundError

  Upvote    Share

Hi,

Please mention the path to the file in your code and it should work fine.
Thanks.

-- Rajtilak Bhattacharjee

  Upvote    Share

Hello,
I created a file in Jupyter and I can't open it.

  Upvote    Share

Hi,

You can try the following command:

f = open("demofile.txt", "r")
print(f.read())

Also, please ensure that you mention the path of the file along with the file name.

Thanks.

-- Rajtilak Bhattacharjee

  Upvote    Share

Hello,
Why "Apple" is missing?

Please explain it

  Upvote    Share

Hi Souvik,

This is because x is storing one value at a time. So first it stores Apple, then it overwrites it and stores Banana. So when you print x, it simply print Banana. You can try using the following statement instead of x = names:

print(names)

This should give you the intended output.

Thanks.

-- Rajtilak Bhattacharjee

  Upvote    Share

Hello,
Jupyter doesn't work properly.
I restart kernel but I am facing the same problem.
Thanks...

  Upvote    Share

Hi, Souvik.

I have rechecked your Jupyter notebook.
It is working fine.
Kindly share the screenshots of the same and I will look into it.

All the best!

-- Satyajit Das

  Upvote    Share

Hello,
Why x represent only single letter of "Banana". I can't understand. Please tell me.

  Upvote    Share

Hi, Souvik.

Here when the for loop will be iterated, then x value will be updated for every iteration and at the end of the loop x="Banana" will be stored. so, x[0] --> will give the first character, that is "B".
similarly x[1] will give you the "a".
All the best!

-- Satyajit Das

  Upvote    Share

Hi,

I have already replied to your query above.

Thanks.

-- Rajtilak Bhattacharjee

  Upvote    Share

Hi,

You do not need the while statement here. You can write the code like this:
list =[1,2,3,4]
count = 1;
for i in list:
if i == 4:
print("item matched")
count = count + 1;
break
print("found at",count,"location");

Happy learning!

Thanks.

-- Rajtilak Bhattacharjee

  Upvote    Share

the jupyter playground on the right hand side of the screen is showing sign in....when i am entering my username and its replying in valid username or password...please help

  Upvote    Share

Hi Eishaan,

Could you please provide us with your email address.

Thanks.

-- Rajtilak Bhattacharjee

  Upvote    Share

eishaansiingh@gmail.com

  Upvote    Share

Hi Eishaan,

Could you please restart your server using the following method and then try once again:
https://discuss.cloudxlab.c...
Thanks.

-- Rajtilak Bhattacharjee

  Upvote    Share

ok sure , thanks

  Upvote    Share

i cannot do that as there are no options like file , edit , view ,etc and also there are no options like logout and control panel...i can only see the notebook , console , files , notes and services tab

  Upvote    Share

how can I copy or save as the practice file of these jupyter to my laptop drive?

  Upvote    Share

Hello Disqus,

Thanks for contacting CloudxLab!

This automatic reply is just to let you know that we received your message and we’ll get back to you with a response as quickly as possible. During business hours (9am-5pm IST, Monday-Friday) we do our best to reply within a few hours. Evenings and weekends may take us a little bit longer.

If you have a general question about using CloudxLab, you’re welcome to browse our below Knowledge Base for walkthroughs of all of our features and answers to frequently asked questions.

- Tech FAQ <https: cloudxlab.com="" faq="" support="">
- General FAQ <https: cloudxlab.com="" faq=""/>

If you have any additional information that you think will help us to assist you, please feel free to reply to this email. We look forward to chatting soon!

Cheers,
The CloudxLab Team

  Upvote    Share

Hi DrB Adh

To download the jupyter notebook you can go to File -> Download as and select the file format in which you want to download it.

-- Sachin Giri

  Upvote    Share

where does these codes available? can you please give the complete link as I have created GitHub account but couldn't see any codes there

  Upvote    Share

Hello Disqus,

Thanks for contacting CloudxLab!

This automatic reply is just to let you know that we received your message and we’ll get back to you with a response as quickly as possible. During business hours (9am-5pm IST, Monday-Friday) we do our best to reply within a few hours. Evenings and weekends may take us a little bit longer.

If you have a general question about using CloudxLab, you’re welcome to browse our below Knowledge Base for walkthroughs of all of our features and answers to frequently asked questions.

- Tech FAQ <https: cloudxlab.com="" faq="" support="">
- General FAQ <https: cloudxlab.com="" faq=""/>

If you have any additional information that you think will help us to assist you, please feel free to reply to this email. We look forward to chatting soon!

Cheers,
The CloudxLab Team

  Upvote    Share

Hi,

Just below the slides there is a link which will take you to our GitHub repository. This repository contains all the required codes.

Thanks.

-- Rajtilak Bhattacharjee

  Upvote    Share

Hi CloudXLab,
Why don’t it letting me to resume the videos? Even I had already done the Q Upto 38 but it’s saying me to start from 28 and taking me to old videos and I am really feeling disgusting on it.

Hope to get the proper solution on it.

Thank you.

  Upvote    Share

Hello Disqus,

Thanks for contacting CloudxLab!

This automatic reply is just to let you know that we received your message and we’ll get back to you with a response as quickly as possible. During business hours (9am-5pm IST, Monday-Friday) we do our best to reply within a few hours. Evenings and weekends may take us a little bit longer.

If you have a general question about using CloudxLab, you’re welcome to browse our below Knowledge Base for walkthroughs of all of our features and answers to frequently asked questions.

- Tech FAQ <https: cloudxlab.com="" faq="" support="">
- General FAQ <https: cloudxlab.com="" faq=""/>

If you have any additional information that you think will help us to assist you, please feel free to reply to this email. We look forward to chatting soon!

Cheers,
The CloudxLab Team

  Upvote    Share

Hi, Dr.

I have rechecked your account, It is working fine. Just restart your server from the control Panel at the right hand side. And below is the link for the Python GITHUB.

https://github.com/cloudxla...

You can fork it.
If still you are getting error, kindly reply to this thread.

All the best!

-- Satyajit Das

  Upvote    Share

def vowel(l):
return l in 'aieuo'
whats problem in this piece of code

  Upvote    Share

What problem are you facing?

  Upvote    Share

hi

  Upvote    Share

Hello can you please Share the Slides from my reference

  Upvote    Share

Hi, Vijay.

Slides are for view only.

You can find the .ipynb files in Github repo.
You can follow this Python for 30 days.
https://www.linkedin.com/po...

All the best!

  Upvote    Share

Hi! Where can I find the code that Sir has made with the comments?

Thank you :)

  Upvote    Share

Hi Smriti
You can look for it in github repository
https://github.com/cloudxla...

  Upvote    Share

fhandle = open("mbox.txt")

showing error for me.

Please let me know why?

  Upvote    Share

fhandle=open("mbox.txt")

fhandle
<_io.TextIOWrapper name='mbox.txt' mode='r' encoding='UTF-8'>

fhandle.read()
''

What is the possible error ?? its not reading the content of the file

  Upvote    Share

My jupyter notebook in the playground is not working. I am able to code but none of the codes are executing. Also if I open jupyter in another tab then its working fine.

  Upvote    Share

Update: Now its working.

  Upvote    Share

startswith is case sensitive.

e.g
sample.txt ----
The economy of India is characterised as a developing market economy.
.......

fhand = open("sample.txt")
for line in fhand :
if line.startswith('The'):
#startswith is case sensitive
print(line)
o/p-- The economy of India is characterised as a developing market economy.

fhand = open("sample.txt")
for line in fhand :
if line.startswith('the'):
#startswith is case sensitive
print(line)

no o/p

please correct me if m wrong

  Upvote    Share

Replace (or string method ) work in same manner as in java, if we would like to act on string we need to create a new string copy of string. Here is ex.

ss = "Hello java"
print(ss)
ss=ss.replace( "java","python")
print(ss)
o/p
Hello java
Hello java
Note: no replacement

ss = "Hello java"
print(ss)
pp=ss.replace( "java","python")
print(pp)

o/p
Hello java
Hello python

Correct me if I am wrong please!.

  Upvote    Share

bro i think u used double quotes(") instead of single quotes(')

  Upvote    Share

found = False
print('Before', found)
for value in [9, 41, 12, 3, 74, 3, 15]:
if value == 3:
found =True
elif value != 3:
found == False
print(found, value)
print("After",found)

i want to print False for values not 3 How can i do that

  Upvote    Share
Abhinav Singh

Please take inspiration from hint

  Upvote    Share

k=[12,23,22,12,1,23,45,67,75,45]
largest=-1
smallest=365
for i in range(len(k)):
if largest<k[i]: largest="k[i]" print('greater="" value="" is="" :',largest)="" if="" smallest="">k[i]:
smallest=k[i]
print('smaller value',smallest)
###what is wrong in this script###

  Upvote    Share
Abhinav Singh

Please take inspiration from the hint

  Upvote    Share

Does Python support increment operator instead of increasing the value of variable by adding 1 ?

  Upvote    Share
Abhinav Singh

Did you check the Python documentation, just curious

  Upvote    Share

Sir,where can I find the slides.....

  Upvote    Share

Hi, Atul.

The python slides are not available right now.
You will be able to download the .html file by maximise the content file.

All the best

  Upvote    Share

Hi Sir,

You talked about the tutorial regarding regex .
Can you share the link for that.

  Upvote    Share
Abhinav Singh

sppos=data.find(' ',atpos)
Hi sir, Why we want to use atpos in the above line of code if we only want to find the space, why cant we simply write
sppos=data.find(' ') to find the space. thanks

  Upvote    Share

Hi, Sodhi.

Here if you only write sppos=data.find(' '), this will give the index "4", but in the code sppos=data.find(' ', atpos) we are trying to find the index of the" space" after the "@" index of 22, so you will get the space at 32.

Thanks

  Upvote    Share

-- Please reply above this line --

Hi, Sodhi.

Here if you only write sppos=data.find(' '), this will give the index "4", but in the code sppos=data.find(' ', atpos) we are trying to find the index of the" space" after the "@" index of 22, so you will get the space at 32.

All the best
--
Best,
Satyajit Das

  Upvote    Share

HI Sandeep sir, have you provided solution codes for the homework assignments,so that we can check our codes against them. thanks

  Upvote    Share

Hi,Sodhi.
You can see the Python programs from our GITHUB link :- https://github.com/cloudxla...

As per assessment is concerned, if your solution is correct you can cross check it by submitting the answer.

All the best.

  Upvote    Share

sir how can i copy the codes in slides to practice in jupyter?

  Upvote    Share

Hi, Anu.

Please try to write the code, this is the best way to learn coding.

Thanks.

  Upvote    Share

Can you please share the link for github l

  Upvote    Share

Hi, I am getting error while executing the below code. Kindly help.

Code:
while True:
line = input(">> ")
if line(0) == '#':
continue
if line == 'Done':
break
print(line)
print("Done!")

Error:
> #sa
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-2-f8c864e171be> in <module>
1 while True:
2 line = input("> ")
----> 3 if line(0) == '#':
4 continue
5 if line == 'Done':

TypeError: 'str' object is not callable

  Upvote    Share

-- Please reply above this line --

Hi,

Please follow the below code.

while True:
line = input("> ")
if line[0] == '#' :
continue
if line == 'done' :
break
print (line)
print ('Done!')

It worked for me.
All the best.

--
Best,
Satyajit Das

  Upvote    Share

mbox.txt file created in jupyter but open command not working

fhandle = open("mbox.txt")
---------------------------------------------------------------------------
FileNotFoundError Traceback (most recent call last)
<ipython-input-14-d91e3b51367c> in <module>
----> 1 fhandle = open("mbox.txt")

FileNotFoundError: [Errno 2] No such file or directory: 'mbox.txt'

  Upvote    Share

Ok I got it. I should create new file in jupyter notebook folder. Earlier I created in jupyter main folder.

  Upvote    Share

how to download the material presented ? I am talking about ppt

  Upvote    Share

Hi Sir, I tried this help("") and it returns two types of output.

1. Methods defined here:
|
| __add__(self, value, /)
| Return self+value.
|
| __contains__(self, key, /)
| Return key in self.

2. split() or capitalize()

In these, I could easily understand the second one, which is essentially function and can be used as string.split() and they return a new string as output.

Could you please explain what does first kind of output mean ?

  Upvote    Share

Hi Manoj, the help command displays the doc string of a function. If you run help("") and help("str"), they both show the same doc string. In Python 3, "" and the str method serve the same purpose of creating string version of object. Hence your first output shows the doc string for the str method. I hope this clears your doubt.

  Upvote    Share

1. How can call by reference be achieved in functions in python ?
2. Does Jupyter automatically print the output in a newline ? Because in C/C++, the std::out prints in a newline only if a new line in passed to it.

  Upvote    Share

>1. How can call by reference be achieved in functions in python ?
You can pass an object to a function.

>2. Does Jupyter automatically print the output in a newline ? Because in C/C++, the std::out prints in a newline only if a new line in passed to it.

print function prints newline character by default. In python 3, you can use the following way for not printing newline: print("something", end="")

  Upvote    Share

Thank you so much Sandeep.

Sso I should pass an object and save the required values to the object's attributes right ?

  Upvote    Share

Yes Sai!

  Upvote    Share

Hi, I hear of the super list which has more variables, operation, look like a lambda function. Could you please demo us more example? thanks.

  Upvote    Share

Probably, you had heard about numpy arrays that we have later.

  Upvote    Share

Hi, how can I access to the slides? thanks.

  Upvote    Share

Are you able to access the slides?

  Upvote    Share