Random numbers and branches in Python

In our last part, we were able to imagine the variables, data types and operators by means of a mathematics game.

Now we will treat the random numbers as well as branches in Python.


Random numbers

In Python, as with Java, a random generator is available to the programmer. The functions of the random number generator are contained in an additional module, which must first be imported. The mathematics game, which we have programmed in the previous section, we edit as follows.



The program does not deliver predefined numbers as a task solution anymore but random tasks. Of course, we initialize the variables within the numbers one through ten, with the tens.

Additional modules can be integrated into the program using the import statement. We can then call the functions of these modules in the notation "module name.function name".

Calling the seed () function of the random module causes the random number generator to initialize with the current system time. Otherwise, it could happen that instead of a random selection always the same numbers are delivered.

The randint() function of the random module returns an integer in the specified range.

Branches

In our previous program, all instructions are executed in order. However, branches are often needed to control the program flow. Within the program, a condition is decided which branch of the program should be executed.

Comparison operators for branches

> greater than

< less than
> = greater than or equal
<= less than or equal
== the same
! = not equal

Simple branching



If the number x is a number greater than 0, then it is a positive value.
Negative value if x is a number less than 0 otherwise it is the number 0.

Now we enter this information into our math program.




Tasks

The program for calculating the tax contribution is changed. The user should be asked to enter his monthly gross salary. If the salary is over 2000 €, 21% tax is payable, otherwise 19%.

In the next part we will discuss the multiple branches. Have fun tinkering.


Kommentare

Beliebte Posts aus diesem Blog

How can I transform a .jar file to a .bat file?

Ein Kleines Spiel mit Altersabfrage

Zufallszahlen und Verzweigungen in Python