how to print a message multiple times on multiple different lines? - python

for starters im new to python and not really good at this kind of thing so dont crusify me ive had bad experiences on reddit.
But, Im able to get user input to repeat the string x amount of times but i cant get it to repeat on different lines.
ive tried \n multiple times (the only thing ive used) in multiple different ways but i just get invalid syntax but i havent really tried to change the base code much.
age = int(input("how old are you?: "))
agedifference = 100 - age
print ("you will be 100 in",agedifference,"years") * int(input("pick a number: "))
so basically i need the user to pick a number for example 4 then repeat the phrase 4 times on 4 different lines.
if you can give a solution with an in depth explanation i would greatly appreciate it (no such thing as to in depth im noob)

Try this (assuming you are on python3):
age = int(input("how old are you?: "))
agedifference = 100 - age
print(f"you will be 100 in {agedifference} years\n" * int(input("pick a number: ")))
For python2:
age = int(input("how old are you?: "))
agedifference = 100 - age
print("you will be 100 in {} years\n".format(agedifference) * int(input("pick a number: ")))

There are plenty of solutions for what you want:
The classic for loop:
for _ in range(num):
print(f"you will be 100 in {agedifference} years")
In python, a print ends the line by default, you can change this behaviour by modifying the end parameter of the function.
The more pythonic one liner:
print('\n'.join([f"you will be 100 in {agedifference} years"] * num))
This one takes advantage of multiple python features:
str.join(iterable) will create a string by concatenating all elements contained in iterable and join them by adding the str in between.
list * int repeats all elements in the list int times.
f-string are one of the many ways to insert variables in string without having to concatenate strings.

You can do something like this as well:
You ask the user to input age and you calculate the agedifference.
Then you ask the user to input the times it has to repeat.
Then use a for loop for looping the output the number of times given by the user.
age = int(input("how old are you?: "))
agedifference = 100 - age
times = int(input("pick a number: "))
for i in range(0,times):
print ("you will be 100 in",agedifference,"years")

What happens with your code is that you are multiplying the return value of print(), which is None, by the number input by the user. Instead, you should repeat the string which is passed in the print() function.
When calling the print() function, here, make sure the string you print ends with a \n. Also, my example needs Python >= 3.6 because of the way the string is formatted (with the 'f' before the string), it is called literal string interpolation.
Finally, to get rid of the last line return which prints an empty line, add the argument end='' to the call to print() (because this character is already in the string your print).
age = int(input("how old are you?: "))
age_difference = 100 - age
repetitions = int(input("pick a number: "))
print(f"you will be 100 in {age_difference} years\n" * repetitions, end='')

Related

program that does something the amount of times a user tells it to not working

I am working in python 3. I am trying to make a program that does something the amount of times a user tells it to. for some reason it is not working. here is my code:
times = input("amount of times: ")
number = 0
while number < int(times):
print ("hello")
number + 1
What is my problem
you are not incrementing number which leads to an infinite loop.
it should be number+=1
while number < int(times):
print ("hello")
number =number+ 1
Try it out
You may want to use a for loop, depending on the program.
Something like this should work for you
times = input("amount of times: ")
for number in range(int(times)):
print("hello")

How do you compare 2 variables with different types of data? [duplicate]

This question already has answers here:
How do I convert all strings in a list of lists to integers?
(15 answers)
Closed 4 years ago.
Compare two variables named target and guess when one is an integer, and one is a string using Python 3.
import random
import sys
target = random.randint(1, 20)
name = input ('Hello, what is your name?')
print ('Hello, %s. I am thinking of a number from 1 to 20. You will have 3 tries, and after each try, I will tell you if the number that I am thinking of is lower or higher. Try to guess it!' % name)
guess = input ('What number do you think I am thinking of?')
if guess == target:
print ('Congratulations! You won! Please play again!')
sys.exit()
else:
print ('You did not guess the number correctly.')
if target < guess:
print ('The number that I am thinking of is smaller than your guess. Try again')
else:
print ('The number that I am thinking of is larger than your guess. Try again!')
You can simply parse the input from string to an integer in this manner:
guess = int(input('What number do you think I am thinking of?'))
And then you can freely compare it to any integer you'd like.

Math with direct input

I just started my first day at uni and there is one of the exercises I am already struggling with. This is the problem: Make code that inputs two given mumbers and output one minus the other
I did this:
number1 = int(raw_input("Type your first number: "))
number2 = int(raw_input("Type your second number: "))
result = number1 - number2
print result
But it was wrong because the input is direct so when the program tested my code it said:
I have always done code that first asks for the information so I have no idea if this is even possible in python or how you do it. Any suggestions are appreciated, thanks.
you need to use :
number1, number2 = map(int, raw_input().split())
result = number1 - number2
print result
In the sample input both the numbers are separated by space, and there is no prompt for the user such as "Type your first number: ", So all yo need to do is take input using raw_input(), then splitting the input on " "(space) by using .split() and then converting each string after splitting to int using the map function.

Python Coding - Vending machine - How to get the user to only enter certain coins?

I'm doing a controlled assessment on python. One of the tasks is to create a vending machine under certain criteria. I'm pretty bad a python and I'm probably being an idiot and doing this wrong.
I want the user to input only 10,20,50,1.00 coins. If the user enters anything other than these coins, I want it to print "Machine doesn't accept these coins".
This is what I have so far:
inp = input("Enter Coins, Note: Machine only accepts 10, 20, 50 and 100 coins: ")
value = [10,20,50,100]
if inp != value:
print("Machine doesn't accept these coins")
else:
print("What would you like to buy?")
Here, you want:
if any(int(coin) not in value for coin in inp.split()):
print("Machine doesn't accept these coins")
What this basically does it split up the input into separate coins, converts them to integers, (because the items in values are integers) then checks if it is not in values, which of course would mean it is invalid.
Finally, this is done until it finds an invalid coin (take a look at any). At that, it will print that the coins are invalid. If it does not, then it will continue to else.

Generating random numbers in python

I'm trying to make a basic dice roller. When i run this program in Codeskulptor, it throws an error on the randint function. Can I not set the range for it using raw_input plugged into variables? Is there a different function I should use?
"""Program to roll random numbers within the ranges set."""
import random
sides_of_die=raw_input("Enter how many sides your die has: ")
number_of_dice=raw_input("Enter number of dice you have: ")
total=sides_of_die*number_of_dice
rollinput=raw_input("Would you like to roll now?")
rollinputcap=rollinput.upper()
if rollinputcap =="Y":
print random.randint(number_of_dice,total)
else:
print "What do you want then?"
raw_input() returns a string, not an integer. To convert it to an integer type, use int():
sides_of_die = int(raw_input("Enter how many sides your die has: "))
number_of_dice = int(raw_input("Enter number of dice you have: "))
What's happening in your code is, you may input "6" and "2", so when you do total = sides_of_die * number_of_dice, you're getting a TypeError
This is just because raw_input returns a string, not a number, while randint accept two numbers as arguments
so you should do
total = int(raw_input(..))
Point is, this is not always secure. Exceptions are very likely to be thrown, so you might want to use a try block; but for the time being, I think it's okay (I'm assuming you're just learning Python).
Another thing, which is rather important:
Look at the exception! If you'd read it, you would have known exactly what the problem was.
Beside the raw_input() problem pointed out by the others, #Mark Ransom's comment is important: the sum of dice value eventually follows normal distribution. See: http://en.wikipedia.org/wiki/Dice#Probability
Your:
if rollinputcap =="Y":
print random.randint(number_of_dice,total)
should be changed to
if rollinputcap =="Y":
sum_dice=[]
for i in range(number_of_dice):
sum_dice.append(random.randint(1, sides_of_dice))
print sum(sum_dice)

Categories

Resources