Learn Python by examples – Ex-01-05
Note there are multiple ways to solve a problem.
Here is one solution.
Exercise 1: Write a program to print Hello World!
Solution:
Concept:
How to use basic print built in function.
print("Hello World!") Output: Hello World!
Exercise 2: Write a program to greet John, say Hello! John
Concept:
How to use basic print built in function.
Solution:
print("Hello! John") Output: Hello! John
Exercise 3: Write a program to greet the user Ex: Hello! [user_name]
Solution:
Concept:
Take user input by using input() built-in function, use variable and print it.
user_name = input("Enter your name :>") print("Hello ! ", user_name) Output: Enter your name :>John Hello ! John
Exercise 4: Write a program to add two numbers and print the result Ex: 20 + 30 => 50
Solution:
Concept:
print() with two arguments, string and an arithmetic expression
print("Sum of 20 and 30 is :", 20 + 30) Output: Sum of 20 and 30 is : 50
Exercise 5: Write a program to add two numbers and print the result Ex: 20 + 30 => 50
Solution:
Concept:
Handling user inputs, arithmetic operation,
use of int() type constructor, string format() usage.
a = int(input("Enter first number :>")) b = int(input("Enter second number :>")) #explicit use of int() type constructor #a = int(a) #b = int(b) print("sum of {} and {} is {}".format(a,b,a+b)) Output: Enter first number :>10 Enter second number :>50 sum of 10 and 50 is 60