Take input from User

In this Python tutorial, we will study that how we can take input from user through keyboard.

Taking input from user in Python is very easy as compared to other programming languages.

 

How to take input

Using input keyword, we can take input from user, and can do whatever we want to do with that input data.

 

Example

Let’s understand it by taking example

 

data=input("Enter some data:")
print("value you enter is:", data)

 

Output

 

Enter some data: learn Python

value you enter is: learn Python

 

Explanation: When we run above example, In the command prompt it will ask some data to be enter. When we enter some value, program take that value to process it.

 

Point to remember: In Python, by default Python will take any data as a string, if you enter numeric data, then also it treats it as string data. Let’s see this by taking example.

 

data=input("Enter some data:")
print("value you enter is:", data)
print("data type of ",data, "is:", type(data))

 

Output

 

Enter some data:123

value you enter is: 123

data type of 123 is: <class 'str'>

 

 

When we enter 123, it should be numeric data, but python treat every data which we take from user input as String data.

 

How to convert String to numeric data?

We have to explicitly convert the data into number if we want to process input data as a numeric data. For that we can use int function to convert String to Numeric data.

 

data=input("Enter some data:")
print("data type of ",data, “before conversion is:”, type(data))
data=int(data)
print("value you enter is:”, data)
print("data type of ",data, “after conversion is:”, type(data))

 

Output

 

Enter some data:123

data type of 123 before conversion is: <class 'str'>

value you enter is: 123

data type of 123 after conversion is: <class 'int'>

 

 

As we see above that using int function we can convert input data into numeric data.

Similarly, we can convert the data into decimal, tuple, list etc.

 

data=input("Enter some data:")
print("value you enter is:”, data)
print("data type of ",data, “before conversion is:”, type(data))
f=float(data)
t=tuple(data)
l=list(data)
print("float value is:",f)
print("data type of ",data,"after conversion is:",type(f))

print("tuple value is:",t)
print("data type of ",data,"after conversion is:",type(t))

print("list value is:",l)
print("data type of ",data, “after conversion is:”, type(l))

 

Output

 

Enter some data:123

value you enter is: 123

data type of 123 before conversion is: <class 'str'>

float value is: 123.0

data type of 123 after conversion is: <class 'float'>

tuple value is: ('1', '2', '3')

data type of 123 after conversion is: <class 'tuple'>

list value is: ['1', '2', '3']

data type of 123 after conversion is: <class 'list'>

 

 

 

Python factorial Program Example

In the Python example series, we will discuss the Python Factorial Program.

 

What is factorial of a number?

First understand what is factorial of a number. Factorial of number n is the multiplication of n with its previous number up to 1 like

n*(n-1) *(n-2) *(n-3) …*1

e.g. if n is 5 then factorial of 5 will be 5*4*3*2*1 which is 120.

 

Some point to remember about factorial

  • 0 factorial is 1
  • 1 factorial is also 1

 

Example

Let’s understand factorial program by example

 

# Python factorial example
# 0! is 1 
# 1! is 1

n=input("Enter the number:")
n=int(n)

#check whether number is 0 or 1
f=1
if n==0 or n==1 :
    print("factorial of", n,"is:", f)

else :
 for i in range(1,n + 1):
       f = f*i
 
print("The factorial of",n,"is",f)

Output

Enter the number:5

The factorial of 5 is 120

 

Explanation:

  • In above example, we ask the user to enter the number.
  • We check whether entered number is 0 or 1, if number is 0 or 1, factorial of number will be 1, as we know that factorial of 0 and 1 is 1.
  • If number is not 0 or 1, then program will go into else part.
  • In else part, for i in range (1, n + 1), we have range function which will start from 1 and go to n+1 i.e. 6, as range function will take the number between 1 to 6. i.e. 1 to 5, so for loop will start from 1 and run till 5.
  • In the next step, f = f*I, we are multiply current number with previous calculated number.
  • At the end, we print the factorial of number.

 

 

local vs global vs non local variable in Python

In this Python basics tutorial we will study about local, global and non local variable of Python with examples.

 

Local Variable

 

Local variables are those variable which are local to some function or block. These variables are accessed only the scope of function inside which they are created.

 

Example of local variable

Let’s understand local variable in Python by taking example

 

#Python local variable example

def f1():
    x=12
    
print(x)

Output

NameError: name 'x' is not defined

 

Explanation:

Here x is defined inside function f1. When we try to access x outside function it throws error that x is not defined. Because x is local variable and can be accessed only the function or block inside where it is created.

 

Global variable

Global variables are those variable which are declare outside any function or methods and can be accessed anywhere in the program, In Python also, we can have global variable.

 

Characteristics of Global Variables

  • Global variables are declared outside any function or block.
  • In Python, there is no need to explicitly write global against variable name.
  • Global variables can be accessed anywhere in the program.

 

Example of global 

 

#Python global variable example
x=2

def f1() :
    
    print(x)
    
f1()
print(x)

Output

 

2

2

 

Non local Variable

 

Python has very interesting variables called non local variables. Non variable are used in nested functions in Python. Nested function are functions inside function. Non local variable act like the global variable.

 

As we study that any variable inside function is local to that function means we cannot access that variable outside the function.

In nested function, one variable of outer function can be global to inner function, this can be achieved by nonlocal keyword.

 

Example of non local variable

Let’s understand this by taking one example:

 

x=12
def f1():
    x=10
    def f2():
         nonlocal x
         x=x+1
         print("value of x inside f2 function",x)
    f2()
    print("value of x inside f1 function",x)

f1()
print("value of global x is",x)

Output

 

value of x inside f2 function 11

value of x inside f1 function 11

value of global x is 12

 

Explanation

  • In above example, x is global variable to program and we have two functions, outer function is f1 and inner function f2.
  • Inside f1 function we have declared one variable x, this x variable is local to function f1 and it has different value than global variable x (at line 1)
  • Inside inner function f2, we have nonlocal variable x, now this nonlocal variable x is bind to variable x defined in function f1, so inside f2 function, variable x will act like global variable. Any alternation or change in value to x inside function f2 will change the value of x of function f1.

That’s why when we did x=x+1 then it will increment value of x which is 10+1=11.

  • Now if we print the value of x inside function f1, it will also be 11 not 10. It shows that local variable x of function f1 acts as global variable to function f2 by using nonlocal keyword.
  • At last, global variable x at line 1, is of value 12. And we print it at last.

 

Nonlocal variables are always bind with local variable to make then non local as name suggested.

 

 

Python except keyword

Python except keyword is used in Python Exception handling. Except is used with try block and if any exception occurs in the program, then except block will executed.

 

Syntax of except

try :

statements

except :

except_statements

except_statements will execute inside except only if any exception occurs in try block.

 

Example of except

 

Let’s understand except with one example

 

x=2
try :
    r=x/0
except:
  print("number is divided by zero exception...")

 

Output

number is divided by zero exception...

after exception

 

In this example, we have variable x having some value when we divide this number with zero. Program throws exception, that exception is handled by except block of Python and statements inside except block will executed.it also did not break the code flow as we can see that print(“after exception“) statement after execute block runs successfully.

 

Let’s try not to put except block and try to run same program.

 

x=2
r=x/0
print("number is divided by zero exception...")
print("after exception")

 

Output

ZeroDivisionError: division by zero

 

See when we did not use except in the program, then program stops after getting zeroDivision error.

 

 

Python del

Python del is used to delete the object in Python. Object could be anything, like number, String, list, tuple, set, class etc.

 

Syntax of del

del object_to_be_deleted

 

Example of del

Here we understand del keyword by taking examples.

 

Delete a variable

#Python del keyword

age=10

print (age)

del age

print(age)

 

Output

 

10

NameError: name 'age' is not defined

 

Explanation

age is variable, when first time we print age value it prints 10.

When we print age value after applying del on age. It throws error that “age” is not defined, because del deleted the age variable.

 

del with String, list and tuple

 

#Python del keyword

name = "Python"
list1=[1,2,3]
tuple1=(10,20,30)

print (name, list1,tuple1)

del name
del list1
del tuple1

print (name)
print(tuple1)
print(list1)

 

Output

Python [1, 2, 3] (10, 20, 30)


NameError: name 'name' is not defined

 

 

Explanation:

In Above example, we have string, list and tuple. When del is applied on these it will delete the String, list and tuple objects respectively.

 

 

del with class

 

#Python del with class

class student :
    rollNo=1
    name="Rocky"
    std="5th"
    
 
print(student.name)

del student

print(student.name)

 

Output

 

Rocky


NameError: name 'student' is not defined.