Tag: Input

N5 Python – Introduction

add2numbersOur 1st Python program makes use of a number of new constructs and variables.

# – Internal Commentary, anything after the # on the same line is ignored by the translator

= (Assignment) – values are assigned to the variables using an equals sign.

input() –  a string is captured from the keyboard using the input() function

int() – this function changes the datatype of the given variable to an integer (Whole number)

Expression – The expression is the right hand side of the =, this is evaluated and any calculations performed, the results are then assigned to the variable on the left hand side of the equals

print() – This function displays a string. The “,” is used to concatenate strings and add a space between them.

 

Python Functions

A function is a predefined block of code which is used then programming. It often contains a number of commands and steps.

Here are some of the functions we have met

print()

This function displays the string that is contained in it parenthesis ().

print(‘Hi there, how are you?)

input()

This function displays the string in its parenthesis but allows the user to enter a string that is then returned and assigned to a variable.

age=input(‘What is your age?’)

str()

Converts the contents of its parenthesis to a string

check=input(‘Is your age ‘+str(age))

len()

Outputs the length (number of characters) of a string or the size (number of elements) in an array

print(‘The length of your name is’,len(name))

float()

Converts a value to a floating point number

weight=float(input(‘How many KG do you weight’))

int()

Converts a value to an integer

age=int(input(‘What is your age?’))

 

Python – Input()

Python input() function returns a string to the assigned variable. This can cause us problems when we want to store integers or floats.

We can use the int() function to convert the string to a integer or the float() function to convert it to a floating point. It is better to do this when you get the input or initialise the variable as you may forget later in the program.

InputInt
The first block of code shows Python returning a string. The second block of code uses a int() to return an Integer