Running python programs

Updated on Jan 07, 2020


You can run python programs in two ways, first by typing commands directly in python shell or run program stored in a file. But most of the time you want to run programs stored in a file.

Lets create a file named hello.py in your documents directory  i.e C:\Users\YourUserName\Documents using notepad (or any other text editor of your choice) , remember python files have .py extension, then write the following code in the file.

print("Hello World")

In python we use print  function to display string to the console. It can accept more than one arguments. When two or more arguments are passed, the print() function displays each argument separated by space.

print("Hello", "World")

Expected output:

Hello World

Now open terminal and change current working directory to C:\Users\YourUserName\Documents using cd command.

CHANGE-CURRENT-WORKING-DIRECTORY.png

To run the program type the following command.

python hello.py

RUNNING-HELLO-WORLD-PROGRAM.png

If everything goes well, you will get the following output.

Hello World

Getting Help #


Sooner or later while using python you will come across a situation when you want to know more about some method or functions. To help you Python has help()  function, here is how to use it.

Syntax:

To find information about class: help(class_name)

To find more about method belong to class: help(class_name.method_name)

Suppose you want to know more about int  class, go to Python shell and type the following command.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
>>> help(int)

Help on class int in module builtins:

class int(object)
| int(x=0) -> integer
| int(x, base=10) -> integer
|
| Convert a number or string to an integer, or return 0 if no arguments
| are given. If x is a number, return x.__int__(). For floating point
| numbers, this truncates towards zero.
|
| If x is not a number or if base is given, then x must be a string,
| bytes, or bytearray instance representing an integer literal in the
| given base. The literal can be preceded by '+' or '-' and be surrounded
| by whitespace. The base defaults to 10. Valid bases are 0 and 2-36.
| Base 0 means to interpret the base from the string as an integer literal.
| >>> int('0b100', base=0)
| 4
|
| Methods defined here:
|
| __abs__(self, /)
| abs(self)
|
| __add__(self, value, /)
| Return self+value.

As you can see help() function spits out entire int class with all the methods, it also contains description where needed.

Now suppose you want to know arguments required for index() method of str class, to find out you need to type the following command in the python shell.

1
2
3
4
5
6
7
8
>>> help(str.index)

Help on method_descriptor:

index(...)
S.index(sub[, start[, end]]) -> int

Like S.find() but raise ValueError when the substring is not found.

In the next post we will learn about data types and variables in python.


Other Tutorials (Sponsors)