0% found this document useful (0 votes)
12 views3 pages

Python Exercises: Functions & Input Handling

The document contains a series of Python exercises focused on using methods and functions for input and output. Exercises include printing a welcome message, calculating the sum of two numbers, and converting height from meters to centimeters and inches. Each exercise provides sample code demonstrating the required functionality and method definitions.

Uploaded by

Full name
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views3 pages

Python Exercises: Functions & Input Handling

The document contains a series of Python exercises focused on using methods and functions for input and output. Exercises include printing a welcome message, calculating the sum of two numbers, and converting height from meters to centimeters and inches. Each exercise provides sample code demonstrating the required functionality and method definitions.

Uploaded by

Full name
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Python Exercises 2 – Method def + print

Exercise 1: Using python print the following syntax: Welcome Samir, you are 26
Where Samir and 26 are 2 values accepted from input

name = input("Enter your name ")


age = int(input("your age is"))
print("Welcome",name,", you are",age)
print("Welcome {}, you are {}".format(name,age))

Exercise 2: Write a python program that reads from input any name then print a
welcoming message with that name using a method called printname (with
parameter).
def printname(n):
print("Welcome", n)

name = input("Enter your name ")


printname(name)

second method

def printname(name):
print("welcome", name)

printname(input("Enter a name "))

Exercise 3: Write a python program that reads from input any name then print a
welcoming message with that name using a function called getname (with
parameter) that return the name

def getname(n):
return "Welcome " + n

1
name = input("Enter your name ")
print(getname(name))

second method

def getname(n):
return "Welcome " + n

print(getname(input("Enter your name ")))

Exercise 4: write a python program that


- Reads 2 numbers from input then
- Print the sum of these 2 numbers using a method called print_sum(with 2
parameters) then
- Get the returned sum using a function called get_sum(with 2 parameters)
then print the sum
- Print the type of every variable on every value change or type change.

def print_sum(a,b):
print(a+b)

def get_sum(a,b):
return a+b

nb1, nb2 = input("Enter 2 numbers ").split()

print(type(nb1))

n1 = int(nb1)

print(type(n1))

n2 = int(nb2)

2
print_sum(n1,n2)
print_sum(nb1,nb2)

somme = get_sum(n1,n2)
somme = get_sum(nb1,nb2)
print(somme)

Exercise 5: Write a Python program that accept from input the height (in meter) and
convert it into centimeter and to inches also (using 2 methods getCM and getInch) that
return the converted values.

Note: 1m = 100 cm = 39.3701 inches (”)

Sample Run

Enter your height in m: 1.75

Height is 175 cm and in inches is 68.89764”

def getCM(h):
return h * 100
def getINCH(h):
return h * 39.3701

height = input("Enter your height in m: ")


height = float(height)
toCM = getCM(height)
toINCH = getINCH(height)
print(" Height is {} cm and in inches is{}\" ". format
(toCM, toINCH))

Common questions

Powered by AI

In Python, to format and print a custom message that includes a user's name and age, you can use both conventional string concatenation and formatted strings. First, collect the user inputs via `name = input("Enter your name ")` and `age = int(input("your age is"))`. Using conventional concatenation, print the message with `print("Welcome", name, ", you are", age)`. Alternatively, use Python's `format` method for greater clarity and control: `print("Welcome {}, you are {}".format(name, age))` .

To create a Python function that prints a welcome message using the user's name input, you can define a function called 'printname' that accepts a parameter 'n'. Inside the function, use the print statement to output the welcome message. For instance: `def printname(n): print("Welcome", n)`. Then, take input from the user using `name = input("Enter your name ")` and pass it to the function `printname(name)` .

To implement a Python function that returns a welcome message with the user's name with input management within the function call, define the function `def getname(n): return "Welcome " + n`. Directly manage the input and call the function using a single line of code: `print(getname(input("Enter your name ")))`. This approach simplifies user input handling by embedding it directly within the function call, thus facilitating streamlined input management and output generation .

In Python, type-casting is essential when dealing with inputs and performing arithmetic operations because input gathered via `input()` is by default of type `str` (string). To perform arithmetic operations, these inputs need to be converted into numerical types, such as `int` or `float`, depending on the operation. Failing to cast types before arithmetic can result in errors or unintended behavior as strings cannot be directly operated on with arithmetic symbols. For example, after inputting numbers with `nb1, nb2 = input("Enter 2 numbers ").split()`, the conversion `n1 = int(nb1)` and `n2 = int(nb2)` ensures the variables are of integer type and ready for addition or other mathematical operations .

To ensure accurate conversion of units in Python when source and destination units have a large magnitude difference, follow these steps: firstly, define clear conversion functions for each target unit, using precise conversion factors, such as `def getCM(h): return h * 100` and `def getINCH(h): return h * 39.3701`. Capture input robustly to handle varied numerical inputs, convert input values to a compatible numerical format like `float`, ensuring precision necessary for large magnitude changes. Finally, implement and test these functions rigorously to verify consistency and accuracy across anticipated input ranges, since even minor inaccuracies can be amplified by the conversion scale .

To implement a Python program that converts a height from meters to centimeters and inches, define two functions: `def getCM(h): return h * 100` for conversion from meters to centimeters, and `def getINCH(h): return h * 39.3701` for conversion from meters to inches. Ask the user to input the height in meters using `height = input("Enter your height in m: ")` and convert it to a float with `height = float(height)`. Call the defined functions with this float value to compute the conversions: `toCM = getCM(height)` and `toINCH = getINCH(height)`. Finally, print the results: `print("Height is {} cm and in inches is {}".format(toCM, toINCH))` .

To modify a Python program for printing different types of variables during their lifecycle, strategically insert `print(type(variable))` statements after each major transformation or operation that involves the variable. This involves initially printing the type right after obtaining input, e.g., `print(type(nb1))` for an input string, then after converting it into an integer, e.g., `n1 = int(nb1); print(type(n1))`, and similarly after any operations that might affect type, such as applying a function or processing. This practice allows you to ensure the expected variable types are maintained and can help debug or trace the flow of data through the program when unexpected behavior occurs .

In Python, a function can be designed to both print directly and return values for subsequent operations by using two separate functions or combining these operations smartly within one function. For direct printing, define a function `def print_sum(a, b): print(a+b)`. For returning values for further use without immediate output, define another function `def get_sum(a, b): return a+b`. By using these functions together, you can separate concerns where one handles the immediate output, and another facilitates further computations or operations by returning the computed result, allowing for flexible program design .

To read two numbers from input and print their sum in Python using functions, first read the input using `nb1, nb2 = input("Enter 2 numbers ").split()` which splits the input into two separate values. Convert these values to integers: `n1 = int(nb1)` and `n2 = int(nb2)`. Then create a function `def print_sum(a,b): print(a+b)` to print the sum of the inputs. Call this function `print_sum(n1, n2)` to get the sum. Additionally, you can define another function `def get_sum(a,b): return a+b` to return the sum. Use this to store and print the sum: `somme = get_sum(n1, n2)` .

In Python, variable type changes can significantly affect the execution of a program, especially when performing operations that require specific data types (e.g., arithmetic operations with non-numeric types). Monitoring these changes helps in identifying type-related errors and ensuring type consistency throughout the program. To monitor the type of a variable, use the `type()` function. For instance, after splitting input into strings, use `print(type(nb1))` to display the current type, then use `n1 = int(nb1)` followed by `print(type(n1))` to verify successful type casting to an integer. Continuously using `type()` after transformations helps track variable type changes and ensures the intended type manipulations before complex operations .

You might also like