Sunday 13 November 2016

Print number pyramid in python

Output should be:

Enter the number of rows:5
1  
1  2  
1  2  3  
1  2  3  4  
1  2  3  4  5  


Code: 

row = int(raw_input("Enter the number of rows:"))  # taking input
for i in range (1,row+1):                                             # iterating from 1 to row+1 
    for j in range(i):                                                      # iterating from 0 to i
        print "%d " % (j + 1),                                         # printing value of j in each loop
    print "\n", 

How to print in Python without newline or space?

code:

row = int(raw_input("Enter a number :"))
for i in range (row):
    print i,


Know how to run python code 


Output: 

$ python print_pattern1.py 
Enter a number :5

0 1 2 3 4

Find an input number is odd or even using Python. Simple program

This program will find an input number is odd or even using Python.

code:

x = int(raw_input("Enter a number: "))
if (x%2 == 0):
        print "%d is Even" % x
else:
        print "%d is Odd" % x


Know how to run python code 

Output: 

$ python odd_even.py
Enter a number: 5
5 is Odd

$ python odd_even.py
Enter a number: 54
54 is Odd


How to run python code?

For running a python code you must have python installed in your system.

After that use these following:

1. open a file using "vi" if you are working in linux terminal or "start" in windows followed by filename (eg. hello_world.py).

2. Write your code in that file. NOTE: do not forget the tabs/space for indentation, it's important for a script.

3. close that file.

4. python hello_world.py


That's it. Done.