Python: Is this a problem in my console settings? - python

I started learning python and now I stuck with this "easy" code. Where is the problem, thanks in advance!
name = input("Enter your name: ")
age = input("Enter your age: ")
print("Hello " + name + "! Your are " + age)
...in the console the strings (name + input) are red and while I´m typing, I can´t see what I´m typing. After I entered a name and press enter, I get this in my console:
Enter your name:Hello Bob! Your are
Enter your age:
Process finished with exit code 0

Related

Python input function, printing

I'm trying to make a simple function where python would calculate age depending on your year input. I've tried several ways and I haven't had luck atm.
ps. sorry, I'm a newbie at this.
ame = input(" Enter your name: ")
age = input(" When were you born?: ")
print("Hello " + name + "! You are " + input (2021 - age)
import datetime
# get the year so it works all the time.
year = datetime.datetime.today().year
name = input(" Enter your name: ")
birth_year = input(" When were you born (year) ?: ")
# calclute the age
age = year - int(birth_year)
print("Hello " + name + "! You are ", age)
There are other ways to print which might look more clean:
print(f'Hello {name}! You are {age}')
or
print("Hello {0}! You are {1}".format(name, age))
To make it a function:
import datetime
def age_cal(birth_year):
# get the year so it works all the time.
year = datetime.datetime.today().year
return year - int(birth_year)
if __name__ == "__main__":
name = input(" Enter your name: ")
birth_year = input(" When were you born (year) ?: ")
age = age_cal(birth_year)
print("Hello {0}! You are {1}".format(name, age))
Here is what you can do: convert age to integer, then subtract it from 2021.
ame = input(" Enter your name: ")
age = input(" When were you born (year) ?: ")
print("Hello " + name + "! You are ",2021- int(age))
Let’s go through the code sample you provided line-by-line.
name = input(" Enter your name: ")
This line creates a variable called name and assigns it to the return value of the built-in function input.
age = input(" When were you born? ")
This does the same, but for the variable age. Note that this stores a string (some characters) not an int. You’ll probably want to convert it, like this:
age = int(age)
Next, you’re trying to print:
print("Hello " + name + "! You are " + input (2021 - age)
But to figure out what to print, Python has to evaluate the return of input(2021-age). (Remember in your code that age was a string; you can’t subtract strings and ints).
You’ve got another problem here- you’re prompting and waiting for input again, but you don’t need to. You’ve already stored the user’s input in the age and name variables.
So what you really want to do is:
print("Hello, " + name + "! You are " + 2021 - age )
Now, if you wanted to be a little more concise, you could also do:
print(f"Hello, {name}! You are {2021 - age}")
You can convert input to int and format your print statement, like below.
name = input("Enter your name: ")
age = int(input("When were you born? (year): ")) # convert input to int
print("Hello {}! You are {} years old".format(name, (2021-age))) # format output
You can make a simple function with datatime like this:
from datetime import date
name = input(" Enter your name: ")
year = int(input(" When were you born?: "))
def calculateAge(year):
today = date.today()
age = today.year - year
return age
print("Hello " + name + "! You are " + str(calculateAge(year)))
This isn't a function for that you have to use def anyway this is the code
Code-
from datetime import date
todays_date = date.today()
name = input(" Enter your name: ")
dob = int(input(" When were you born?: "))
print("Hello " + name + "! You are " + todays_date.year - dob)

Get Input from User then Use it in a Sentence

Hello everyone I need your help.
I am running this plain code on atom
name =input("What's your name? ")
print("Nice to meet you " + name + "!")
age = input("Your age? ")
print("So, you are already " + age + " years old, " + name + "!")
it is showing me the sand time icon at the bottom and doesn't give any output.
for other commands like
name = "Nick"
print(name)
is working perfectly.
I dont know what to do please help.
ptyhon version is 3.6.9

Program closing when it shouldn't

I'm makeing a text based game.
the user is asked to enter:
name
difficulty
skill level
However, once the user inputs the difficulty the program closes.
Any help will be appreciated.
OH AND PLEASE COULD YOU NOT JUST DOWN-VOTE WITHOUT GIVING AN EXPLANATION, NOT EVERYONE IS A PYTHON MASTER.
P.S. sorry for broken english
while True:
print("Welcome to 'The imposible quest'")
print("""
""")
name_charter = str(input("What's your name adventurer? "))
difficulty = str(input("Please choose the difficulty level(easy, normal, hard): "))
while set_difficulty==0:
if difficulty=="easy":
max_skill_start = 35
player_max_hp = 120
set_difficulty = 1
elif difficulty=="normal":
max_skill_start = 30
player_max_hp = 100
set_difficulty = 1
elif difficulty=="hard":
max_skill_start = 25
player_max_hp = 80
set_difficulty = 1
else:
print("ERROR, the option you chose is not a valid difficulty!")
print("Hello" + nam_char + "/n /n Please choose your abilities, keep in mind that you can't spend more than" + max_skill_start + "points in your habilities: ")
strength, dexterity, intelligence, perception, charm, combat, crafting, tradeing = input("Strength: "), input("Dexterity: "), input("Intelligence: "), input("Perception: "), input("Charm: "), input("Combat: "), input("Crafting: "), input("Tradeing: ")
end_prg = str(input("Do you want to close the program(yes/no)? "))
if end_prg=="yes":
quit()
elif end_prg=="no":
print("""
""")
You just need to set the set_difficulty to 0 before the while loop. Also I see you are printing out big empty lines, you can also use the print("\n") this will create a newline. You can add multiple by *by number desired :
print("\n"*10) //prints out 10 newlines.

Character Input Not Halting Program

I am new to Python and am encountering an error when I use the following:
name = input("Would you please enter your name: ")
age = int(input("Would you please enter your age: "))
year = str((2017 - age)+100)
print("Your name is " + name + "and you will turn 100 years old in the year " + year)
When I open Python 3.5.3 from the Command Prompt (Windows 10), and I copy and paste this code from my notepad, the first lines appear as:
>>>> name = input("Would you please enter your name: ")
Would you please enter your name: age = int(input("Would you please enter
your age: "))
How do I circumvent this issue? From what I've read the program is supposed to break after encountering "input."
For reference I am starting to work through problem 1 from http://www.practicepython.org/exercise/2014/01/29/01-character-input.html
In Python interactive mode lines are executed at each line break so in your example is name is assigned the value of the string 'age = int(input("Would you please enter your age: "))'.
If you want to copy the full code into the interactive prompt and have it execute only after all lines then you have to add ;\ to the end of each line before you copy the text. The ; shows the assignment has ended but the \ indicates line continuation so the code isn't executed immediately:
>>> name = input("Would you please enter your name: ") ;\
... age = int(input("Would you please enter your age: "))
Would you please enter your name: NicolausCopernicolaus
Would you please enter your age: 29
>>> name
'NicolausCopernicolaus'
>>> age
29

Saving Raw_input to a list when used in a While Loop

I have already posted a question today and it had 2 problems on it. One of which was solved perfectly, then it got a little complicated. So forgive me but I am posting the other question separately as it confused some peeps:
I am new to python so apologies in advance. Any help is much appreciated. I have been stuck on this code for 2weeks now and I have tunnel vision and cannot work it out:
Basically our assignment was to get to grips with Object-Oriented Programming. We unfortunately have to use "get" and "set" which I've learnt a lot of people dislike, however, as per our tutor we have to do it like that. We were told tp create a program whereby the user is presented with a screen with 3 options. 1. adding a student. 2. viewing a student and 3. removing a student.. within my AddStudent function I have to ask the user to enter fname Lname age degree studying id number (these are the easy bits) and also module name and grade for each module, I have managed to create a loop whereby it will ask the user over and over to enter modules and corresponding grades and will break from said loop when the user enters -1 into the modulname field. However, when trying saving it to a list named students[] ... (which is at the very top of my code above all functions, to apparently make it global) it saves all input from the user re: age name etc but when it comes to saving module names and grades it only saves the last input and not the multiple inputs I need it to. I am unsure if it is within my AddStudent function where it isn't saving or within my ViewStudent function: Both are below (remember I HAVE to use the GET and SET malarky) ;)
students[] # Global List
def addStudent():
print
print "Adding student..."
student = Student()
firstName = raw_input("Please enter the student's first name: ")
lastName = raw_input("Please enter the student's last name: ")
degree = raw_input("Please enter the name of the degree the student is studying: ")
studentid = raw_input("Please enter the students ID number: ")
age = raw_input("Please enter the students Age: ")
while True:
moduleName = raw_input("Please enter module name: ")
if moduleName == "-1":
break
grade = raw_input ("Please enter students grade for " + moduleName+": ")
student.setFirstName(firstName) # Set this student's first name
student.setLastName(lastName)
student.setDegree(degree)# Set this student's last name
student.setGrade(grade)
student.setModuleName(moduleName)
student.setStudentID(studentid)
student.setAge(age)
students.append(student)
print "The student",firstName+' '+lastName,"ID number",studentid,"has been added to the system."
........................
def viewStudent():
print "Printing all students in database : "
for person in students:
print "Printing details for: " + person.getFirstName()+" "+ person.getLastName()
print "Age: " + person.getAge()
print "Student ID: " + person.getStudentID()
print "Degree: " + person.getDegree()
print "Module: " + person.getModuleName()
print "Grades: " + person.getGrade()
your problem is that the module is a single variable you keep changing. instead, make it a list.
while True:
moduleName = raw_input("Please enter module name: ")
if moduleName == "-1":
break
grade = raw_input ("Please enter students grade for " + moduleName+": ")
should be something like
modules = []
while True:
moduleName = raw_input("Please enter module name: ")
if moduleName == "-1":
break
grade = raw_input ("Please enter students grade for " + moduleName+": ")
modules.append((moduleName, grade))
add a new variable to student which is "Modules" and is a list.
and then modules will be a list of tuples which are (moduleName, grade) and to display them, change the line in viewstudent from:
print "Module: " + person.getModuleName()
print "Grades: " + person.getGrade()
to:
for module, grade in person.getModules():
print "Module: " + module
print "Grades: " + grade
It seems you need something like this:
modules = {}
while True:
module_name = raw_input("Please enter module name: ")
if module_name:
grade = raw_input ("Please enter students grade for " + module_name +": ")
modules[module_name] = grade
Modules is a dictionary ("hash map" in other languages), each mod name is key and grades are values, or you could also do it with tuples, wherever floats your boat.
Instead of checking for -1 as a stop condition you check if is true, in python anything empty is evaluated to false.

Categories