Python First Program

How to create a python program?

Create this program in file name 'text.py'.
#!/usr/bin/python                
print "First Python Code!";
here operating system will use first line to know which interpreter to run to execute the scripts if python scripts file is made as executable file.

How to run the python program?

Run this program using python command.
$python test.py
For this case, first line #!/usr/bin/python is not required.
print statement is used to print the string in command line.

Is there any alternate to run python program?

Alternate way to run python program:
$ chmod +x test.py # Makes the python file executable
$./test.py
Output:
First Python Code!

To get user input in python

raw_input method is used to get the input from user and returns in string format.
#!/usr/bin/python                                                               
                                                                                
input_str = raw_input("Please enter a string: ")                                
                                                                                
print("Entered string is %s" % input_str) 
Output:
$python first_input.py
Please enter a string: welcome to python
Entered string is welcome to python
Suppose we need to get input as integer format, type casting needs to be done as below.
# file name is first_input.py
#!/usr/bin/python                                                               
                                                                                
num = int(raw_input("Please enter an integer: "))                               
                                                                                
print("Entered number is %d" % num) 
Output:
$python first_input.py
Please enter an integer: 34
Entered number is 34
Python interpreter throws type error if print statement incorrectly uses type.
print function gets input_str as string format instead of integer which is expected.
$ python first_input.py
Please enter a string: welcome to python
Traceback (most recent call last):
  File "first.py", line 5, in 
    print("Entered string is %d" % input_str)
TypeError: %d format: a number is required, not str



Privacy Policy  |  Copyrightcopyright symbol2020 - All Rights Reserved.  |  Contact us   |  Report website issues in Github   |  Facebook page   |  Google+ page

Email Facebook Google LinkedIn Twitter
^