Featured Post

Python map() and lambda() Use Cases and Examples

Image
 In Python, map() and lambda functions are often used together for functional programming. Here are some examples to illustrate how they work. Python map and lambda top use cases 1. Using map() with lambda The map() function applies a given function to all items in an iterable (like a list) and returns a map object (which can be converted to a list). Example: Doubling Numbers numbers = [ 1 , 2 , 3 , 4 , 5 ] doubled = list ( map ( lambda x: x * 2 , numbers)) print (doubled) # Output: [2, 4, 6, 8, 10] 2. Using map() to Convert Data Types Example: Converting Strings to Integers string_numbers = [ "1" , "2" , "3" , "4" , "5" ] integers = list ( map ( lambda x: int (x), string_numbers)) print (integers) # Output: [1, 2, 3, 4, 5] 3. Using map() with Multiple Iterables You can also use map() with more than one iterable. The lambda function can take multiple arguments. Example: Adding Two Lists Element-wise list1 = [ 1 , 2 , 3 ]

2 User Input Python Sample Programs

Here are the Python programs that work on taking user input and giving responses to the user. These are also called interactive programs. 


Python enables you to read user input from the command line via the input() function or the raw_input() function. Typically, you assign user input to a variable containing all characters that users enter from the keyboard. User input terminates when users press the <return> key (included with the input characters).


User input programs


#1 User input sample program


The following program takes input and replies if the given input value is a string or number.


my_input = input("Enter something: ") 
try: 
    x = 0 + eval(my_input) 
    print('You entered the number:', my_input) 
except: 
    print(userInput,'is a string')


Output


Enter something: 

100

You entered the number: 100

** Process exited - Return Code: 0 **

Press Enter to exit terminal. 


#2 User input sample program


The following program takes two inputs from the user and calculates the sum.


sum = 0
msg = 'Enter a number:'
val1 = input(msg)

try:
  sum = sum + eval(val1)
except:
  print(val1,'is a string')

msg = 'Enter a number:'
val2 = input(msg)

try:
  sum = sum + eval(val2)
except:
  print(val2,'is a string')

print('The sum of',val1,'and',val2,'is',sum)


Output

Enter a number:
100
Enter a number:
200
The sum of 100 and 200 is 300


** Process exited - Return Code: 0 **
Press Enter to exit terminal


Related

Comments

Popular posts from this blog

How to Fix datetime Import Error in Python Quickly

SQL Query: 3 Methods for Calculating Cumulative SUM

Python placeholder '_' Perfect Way to Use it