Why I cannot run multiple Print() statements in command prompt? - python-3.x

I am trying to run this following code
It runs ok directly from the third.py file
But if I type the code in the Command Prompt it gives me en error
Can anyone point out my mistake here.

This is what the code would look like if you opened a file using IDLE. Note the indentation is necessary. The blastoff line begins in column 1 because it is the first statement after the while loop.
n = 5
while n > 0 :
print(n)
n = n - 1
print('Blastoff!')
In the IDLE interactive mode, you would enter lines 1 and 2. You would see that after entering line 2 that the prompt automatically indented so that you can begin entering statements that are part of the while loop, and the >>> prompt disappears, so that you would enter lines 3 and 4 like this:
>>> n = 5
>>> while n > 0 :
print(n)
n = n - 1
At this point, you need to press enter to complete the while loop.
If you enter the blastoff line before doing so at the same indentation as lines 3 and 4 then you will create a logic error where the code will work but it will be incorrect.
If you backspace and enter the blast off line then you will get the syntax error you encountered.
So press enter to complete while loop. It will execute and produce output like so:
5
4
3
2
1
>>>
...and then it will return your prompt back again. You can then enter the blastoff line after the prompt:
>>> print('Blastoff!')
...and the output will be:
Blastoff!

Related

Reads a series of lines Python

Can someone enlighten me how to do this?
Write a Python program that reads a series of lines one by one from the keyboard (ending by an empty line) and, at the end, outputs the number of times that the first line occurred. For example, if it reads
hello
world
We say hello
hello
Birkbeck
hello
it would output 3 since the first line ("hello") occurred three times.
You may assume that the user enters at least two non-empty lines before the empty line.
not sure if you want to separate word with spaces or with the newline character and if we count the first occurence.
This is a sample solution for spaces separation between words. This works for the example that you provided
freq_dict = {}
word = input().split()
for w in word:
if w not in freq_dict.keys():
freq_dict[w] = 0
else:
freq_dict[w] += 1
print(freq_dict[word[0]])

How to navigate to indendation levels in vim

I have the following code (line numbers included):
1 def test():
2 a = 1
3 b = 1
4 c = 1
5 d = 1
6 if a == 1:
7 print('This is a sample program.')
And the cursor is on line 7, the last line. Is there a fast, and ideally one key, way to navigate up to line 6, which is one indentation level up, and then, on the next key press, to line 1, one indentation level up again? Conversely, is there a matching method to "drill down" that way?
There is a plugin for that: https://github.com/jeetsukumaran/vim-indentwise
The mappings it provides that match what you are looking for are:
[- : Move to previous line of lesser indent than the current line.
[+ : Move to previous line of greater indent than the current line.
]- : Move to next line of lesser indent than the current line.
]+ : Move to next line of greater indent than the current line.
Then, if you really wanted to do what you asked for in a single keypress, you can remap them like so, for example:
nmap - [-
nmap + ]+

line.strip() cause and effects to my second statement

I have 3 parts in my code. My first part tells me what line number the condition is on for line1. My second part tells me what line number the condition is on for line2. The last part makes the numbers as a range and prints out the range.
The first part of the code: I get a result of 6 for num1.
For the second part of the code I get 24 when i run it by itself but a 18 when i run it with part 1.
Then at the 3rd part i index the file and i try to get the proper lines to print out, but they dont work because my first part of my code is changing numbers when i have both conditions running at the same time.
Is there a better way to run this code with either just indexing or just enumerating? I need to have user input and be able to print out a range of of the file based off the input.
#Python3.7.x
#
#
import linecache
#report=input('Name of the file of Nmap Scan:\n')
#target_ip=input('Which target is the report needed on?:\n')
report = "ScanTest.txt"
target_ip = "10.10.100.2"
begins = "Nmap scan report for"
fhand = open(report,'r')
beginsend = "\n"
#first statement
for num1,line1 in enumerate(fhand, 1):
line1 = line1.rstrip()
if line1.startswith(begins) and line1.endswith(target_ip):
print(num1)
print(line1)
break
#second statement
for num2,line2 in enumerate(fhand, 1):
line2 = line2.rstrip()
if line2.startswith(beginsend) and num2 > num1:
print(num2)
print(line2)
break
with open('ScanTest.txt') as f:
linecount = sum(1 for line in f)
for i in range(num1,num2):
print(linecache.getline("ScanTest.txt", i))
The first part of the code: I get a result of 6 for num1. for the second part of the code I get 24 when i run it by itself but a 18 when i run it with part 1.
Obviously the second part continues reading the file where the first part stopped.
The minimal change is to put
num2 += num1
after the second loop, or just change the 3rd loop to for i in range(num1, num1+num2):. The condition and num2 > num1 within the second loop is to be removed.

How to sleep in Python 3 and remain in the same line?

I want to print a message with end=''
Sleep for 1 second
Remain on the same line
Erase the previous message using '\b'
Print a new message
Back to step 1
Example:
First output:
1
Second output:
2
Third output:
3
Remains in the same line
NOT: 123
Are you set on using \b? You can use \r to move the cursor back to the beginning of the line, which will let you write over stuff that is already there. If there's a chance that later lines will be shorter than previous ones, you should pad the new lines with whitespace on the right. Something like:
def f(x):
for i in range(1, x+1):
print(end='\r', flush=True)
print('**{}**'.format(i), end='', flush=True)
time.sleep(1)
f(3)

Python 3.x - don't count carriage returns with len

I'm writing the following code as part of my practice:
input_file = open('/home/me/01vshort.txt', 'r')
file_content = input_file.read()
input_file.close()
file_length_question = input("Count all characters (y/n)? ")
if file_length_question in ('y', 'Y', 'yes', 'Yes', 'YES'):
print("\n")
print(file_content, ("\n"), len(file_content) - file_content.count(" "))
It's counting carriage returns in the output, so for the following file (01vshort.txt), I get the following terminal output:
Count all characters (y/n)? y
0
0 0
1 1 1
9
...or...
Count all characters (y/n)? y
0
00
111
9
In both cases, the answer should be 6, as there are 6 characters, but I'm getting 9 as the result.
I've made sure the code is omitting whitespace, and have tested this with my input file by deliberately adding whitespace and running the code with and without the line:
- file_content.count(" ")
Can anyone assist here as to why the result is 9 and not 6?
Perhaps it isn't carriage returns at all?
I'm also curious as to why the result of 9 is indented by 1 whitespace? The input file simply contains the following (with a blank line at the end of the file, line numbers indicated in the example):
1. 0
2. 0 0
3. 1 1 1
4.
...or...
1. 0
2. 00
3. 111
4.
Thanks.
If you want to ignore all whitespace characters including tabs and newlines and other control characters:
print(sum(not c.isspace() for c in file_content))
will give you the 6 you expect.
Alternatively you can take advantage of the fact the .split() method with no argument will split a string on any whitespace character. So split it into non-space chunks and then join them all back together again without the whitespace characters:
print(len(''.join(file_content.split())))
You're getting 9 because the content of the file could be interpreted like:
file_content = "0\n0 0\n1 1 1\n"
and you're only matching the white spaces (file_content.count(" ")).
In order to count only the characters you'd either:
read line by line the file, or
use a regexp to match white space.
For the indenting of 9: print processes the commas as outlined here

Resources