Introduction to Python
First Python Program
Check the updated DevOps Course.
Course Registration link:
Course Link:
YouTube link:
This is the introduction to Python Series in which the below Program shows how to take input from Keyboard and ask for Name and Age
#First Python Program to ask for age and name
print("What is your name:")
name = input()
print("Hello: " + name)
print("Length of your name is: ")
print(len(name))
print("What is your age: ")
age = input()
print("You are growing old " + name + " " + age)
Output
python3 firstprogram.pyWhat is your name:
Prashant
Hello: Prashant
Length of your name is:
8
What is your age:
33
You are growing old Prashant 33
Now let see what going on
- Python reads the program from the top and read line by line(which refer as execution)
- # is used as comment to make your program more readable and completely ignored by Python
- print is a function(mini-programs in our program)which display the values passed to it
- When input() function is called python is waiting for user to enter some text via keyboard,it like a variable which holds some value(input always holds the string value)
- Then we are performing string concatenation
- What len does it takes a string value and returns an integer value of the string length
>>len("Prashant")
8
As mentioned above input return a string so we must cast it, if we are working with numbers
>>> age = input(“What is your age: “)What is your age: 5>>> type(age)<class ‘str’># Which is not what we are expecting
>>> age * 5'55555'
And the way to do it
>>> age = int(input(“What is your age: “))What is your age: 5>>> age * 525
Now let look at some data types,first and second are self explanatory but in the last case, as we see it return as string
>>> a = 4>>> type(a)<class ‘int’>>>> b = “hello”>>> type(b)<class ‘str’>>>> c = “4”>>> type(c)<class ‘str’>
As we can’t perform mathematical operation on string, we must need to convert them to integer
>>> “4” + 2Traceback (most recent call last):File “<stdin>”, line 1, in <module>TypeError: must be str, not int>>> int(“4”) + 26
Same way, if we need to concatenate string with integer we need to convert integer to string
>>> “how old are you” + 2Traceback (most recent call last):File “<stdin>”, line 1, in <module>TypeError: must be str, not int>>> “how old are you” + “ 2”‘how old are you 2’
Some interesting thing to note while we are doing variable assignment/swapping variable in case of Python
>>> x = 1>>> y = 2>>> y = x>>> x = y>>> x1>>> y1
We are not expecting this output, we want x=2 and y=1 so we need to be really careful so the better way to do that is using extra variable called temp.
>>> x = 1>>> y = 2>>> temp = y>>> y = x>>> x = temp>>> x2>>> y1